Thursday, 18 October 2018

parallel records of the keys to the flask session

I can't find solution on the parallel records of the keys to the flask session.

we have the simple application,

import time

from flask import Flask, session
from flask_session import Session

app = Flask(__name__)
SESSION_TYPE = 'redis'
app.debug = True
app.config.from_object(__name__)
Session(app)


@app.route('/set/<value>')
def set_value(value):
    """ This route is emulate long time request to multi real routes."""
    time.sleep(1)
    session['key_%s' % value] = 'done'
    return 'ok\n'


@app.route('/keys')
def keys():
    return str(session.keys()) + '\n'


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5007, threaded=True)

to test the problem create shell script like this (sorry if you use windows)

#!/bin/bash
# set session
curl -c 'cookie'  http://localhost:5007/keys
# run parallel
curl -b 'cookie'  http://localhost:5007/set/key1 && echo "done1" &
curl -b 'cookie'  http://localhost:5007/set/key2 && echo "done2" & 
curl -b 'cookie'  http://localhost:5007/set/key3 && echo "done3" &
wait
# get result
curl -b 'cookie'  http://localhost:5007/keys

as result we have next:

user@dev:~/dev/sess_keys$ sh sh_test.sh 
dict_keys(['_permanent'])
ok
ok
ok
done3
done1
done2
dict_keys(['_permanent', 'key_key2'])
user@dev:~/dev/sess_keys$ sh sh_test.sh 
dict_keys(['_permanent'])
ok
done3
ok
ok
done2
done1
dict_keys(['_permanent', 'key_key1'])

the project is not new, and the problem became active after the base has grown significantly. So i try to find the solution, thinking about to make some proxy for session that will fix such collisions or exclude use session in the project. May be someone has advanced solution for the trouble.



from parallel records of the keys to the flask session

No comments:

Post a Comment