简体   繁体   中英

Maintaining session data in Python Flask

I have a client which sends JSON data to a server. This JSON data contains a budget and epsilon value. 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. If so, it initializes the used_budget to 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 . 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.

Problem : When I am sending an initial request from a client, a new session is initialized and epsilon is added. 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. 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. 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. When you send the request from browser, browser attached the session cookie to the new request. Such is not the case when you are making a request any request using IDE client. The IDE client is not maintaining any session cookie hence every time a new session is getting created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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