python - How can a unique Rserve connection be stored per session? -


i'm writing small flask application , having connect rserve using pyrserve. want every session initiate , maintain own rserve connection.

something this:

session['my_connection'] = pyrserve.connect() 

doesn't work because connection object not json serializable. on other hand, this:

flask.g.my_connection = pyrserve.connect() 

doesn't work because not persist between requests. add difficulty, doesn't seem though pyrserve provides identifier connection, can't store connection id in session , use retrieve right connection before each request.

is there way accomplish having unique connection per session?

we need common location create rserve connection each user. simplest way run multiprocessing.manager separate process.

import atexit multiprocessing import lock multiprocessing.managers import basemanager import pyrserve  connections = {} lock = lock()   def get_connection(user_id):     lock:         if user_id not in connections:             connections[user_id] = pyrserve.connect()          return connections[user_id]   @atexit.register def close_connections():     connection in connections.values():         connection.close()   manager = basemanager(('', 37844), b'password') manager.register('get_connection', get_connection) server = manager.get_server() server.serve_forever() 

run before starting application, manager available:

python rserve_manager.py 

we can access manager app during requests using simple function. assumes you've got value "user_id" in session (which flask-login do, example). ends making rserve connection unique per user, not per session.

from multiprocessing.managers import basemanager flask import g, session  def get_rserve():     if not hasattr(g, 'rserve'):         manager = basemanager(('', 37844), b'password')         manager.register('get_connection')         manager.connect()         g.rserve = manager.get_connection(session['user_id'])      return g.rserve 

access inside view:

result = get_rserve().eval('3 + 5') 

this should started, although there's plenty can improved, such not hard-coding address , password, , not throwing away connections manager. written python 3, should work python 2.


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -