Home > Software design >  How to assign Redis key names to Flask app users?
How to assign Redis key names to Flask app users?

Time:02-14

I have a Flask app which stores user sessions in Redis on localhost.
User sessions are managed by Flask-Session module:

import flask
import redis  
import flask_session

app = flask.Flask(__name__)

app.secret_key = b'Test123'

app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_KEY_PREFIX'] = 'flask_session_'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_REDIS'] = redis.from_url('redis://localhost:6379', password='Test123')

server_session = flask_session.Session(app)

I'd like to know which Redis session key name belongs to which user or device.
For example I'd like to add client's IP addresses to Redis key names.
Is it possible?
When I try to get client's IP address and set it as a key prefix like this:

ip = flask.request.environ.get('REMOTE_ADDR')

app.config['SESSION_KEY_PREFIX'] = 'flask_session_'   ip

I get this message in Apache error.log:

RuntimeError: Working outside of request context.
[Fri Feb 11 22:19:14.371919 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] This typically means that you attempted to use functionality that needed
[Fri Feb 11 22:19:14.371930 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] an active HTTP request. Consult the documentation on testing for
[Fri Feb 11 22:19:14.371941 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] information about how to avoid this problem.

CodePudding user response:

I've figured it out.
Obviously you can't run flask.request.environ.get('REMOTE_ADDR') before the request, even with @app.before_request.
So, to identify sessions (Redis key names) and assign them to app users (so I know which session/key belongs to which user) my app now writes Flask-Session SID along with the logged in username to the Apache error.log:

app.logger.warning('User '   login   ' logged in. Flask-Session SID: '   str(flask.session.sid)   '. Flask-Login session ID: '   str(flask.session['_id'])   '.')

Flask-Session SID is the Redis key name.
Another way would be storing the username or IP address in flask.session after the request (after the users login), SCAN-ning the Redis KEYS for values (usernames or IP address) and RENAME-ing the keys by pattern.

  • Related