简体   繁体   English

在 Python Flask 中维护会话数据

[英]Maintaining session data in Python Flask

I have a client which sends JSON data to a server.我有一个客户端将 JSON 数据发送到服务器。 This JSON data contains a budget and epsilon value.此 JSON 数据包含budgetepsilon值。 The server receives the data and checks if the used_budget is None or in other words, if that is the first request from the client.服务器接收数据并检查used_budget是否为None或者换句话说,如果这是来自客户端的第一个请求。 If so, it initializes the used_budget to 0.0.如果是,它used_budget初始化为 0.0。

The condition is every time the client sends a JSON payload, the epsilon value is added to the used_budget and the used_budget is compared with budget .条件是每次客户端发送 JSON 负载时,将epsilon值添加到used_budget并将used_budgetbudget进行比较。 If the used_budget is less than budget then the server queries a database and returns some result to the client else the server should stop accepting requests from the client.如果used_budget小于budget则服务器查询数据库并向客户端返回一些结果,否则服务器应停止接受来自客户端的请求。

Problem : When I am sending an initial request from a client, a new session is initialized and epsilon is added.问题:当我从客户端发送初始请求时,会初始化一个新会话并添加epsilon The server returns the result to the client as expected.服务器按预期将结果返回给客户端。 BUT, when I send another request from the client, instead of treating it as a same session, the server initializes a new session and the used_budget value is set to 0.0 again.但是,当我从客户端发送另一个请求时,服务器没有将其视为同一个会话,而是初始化一个新会话,并将used_budget值再次设置为 0.0。 The condition checking never occurs.条件检查永远不会发生。

This is the server side code:这是服务器端代码:

class GetParams(Resource):
    def get(self):

    client_request = json.loads(list(dict(request.args).keys())[0])  # Stores the request in JSON format
    budget = client_request['budget']
    epsilon = client_request['epsilon']
    used_budget = session.get('used_budget')  # used_budget used a session variable

    # If Client sends the first request then initialize used_budget to 0.0
    if used_budget == None:
        set_used_budget()

    # Check if client has budget for sending queries for a session
    if (session['used_budget'] < float(budget)):
        session['used_budget'] = session.get('used_budget') + float(epsilon)
        result = write_file(client_request)  # Write request to file and store the returned query result
        print("used budget " + str(session['used_budget']))
        return result # Return the query result to the client
    else:
        error_message = "Budget exceeded - Cannot process queries"
        return error_message

api.add_resource(GetParams, '/data')  # Route for get()    
if __name__ == '__main__':
    app.run(port='5890', threaded=True)

Here is the client side code:这是客户端代码:

# Client sends this data in url
data = {
    'query': 'SELECT count(*) FROM accounts',
    'epsilon': '1.0',
    'budget': '2.0',
}

# Localhost url
url = 'http://127.0.0.1:5890/data'

# Client sends Get request
 session = requests.Session()    

resp= session.get(url, params=json.dumps(data))

# Client prints the data returned by the server in JSON
print(resp.json())

# Client prints the response code
print(resp)

The code works fine when I run it from a browser (ie, sessions are maintained when I use two different browsers) but a new session is started when I ping the server from the client using an IDE.当我从浏览器运行代码时,该代码工作正常(即,当我使用两个不同的浏览器时,会话会得到维护),但是当我使用 IDE 从客户端 ping 服务器时,会启动一个新会话。 Can anyone tell me what am I doing wrong over here?谁能告诉我我在这里做错了什么?

This is happening because flask session works little differently.发生这种情况是因为烧瓶会话的工作方式略有不同。 The session data is passed to the client along with the response and stored on client as session cookie.会话数据与响应一起传递给客户端,并作为会话 cookie 存储在客户端上。 When you send the request from browser, browser attached the session cookie to the new request.当您从浏览器发送请求时,浏览器会将会话 cookie 附加到新请求中。 Such is not the case when you are making a request any request using IDE client.当您使用 IDE 客户端发出任何请求时,情况并非如此。 The IDE client is not maintaining any session cookie hence every time a new session is getting created. IDE 客户端不维护任何会话 cookie,因此每次创建新会话时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM