Keeping objects between requests

45 views
Skip to first unread message

Joel Samuelsson

unread,
Apr 6, 2020, 1:53:06 AM4/6/20
to web2py-users
I'm using cassandra as a database with web2py and would like to keep the cassandra session between requests to reduce session recreation and lower latencies. Is this a bad idea? And how would I do it?
Any tips appriciated!

Val K

unread,
Apr 6, 2020, 5:51:12 AM4/6/20
to web2py-users
You can save any object in the module or current, but if you use more than one worker you will have independent instance of that object per worker

Joel Samuelsson

unread,
Apr 7, 2020, 5:15:44 AM4/7/20
to web2py-users
Did this in the top of a controller:
from gluon import current
try:
 
if current.ts_db is not None:
   
Databases.setTSDB(current.ts_db)
except AttributeError:
 current
.ts_db = Databases.setTSDB()

Databases is a model and setTSDB looks liks this:
 @staticmethod
 
def setTSDB(db = None):
   
if db is None:
     logger
.debug("Creating new TS DB")
     db
= CassandraConnection([TS_DB_URL], TS_DB_PORT)
   
DriverFactory.setDB(db)
 
return db

Whenever I make a request I get the "Creating new TS DB" log so the object doesn't seem to be saved. Any ideas why?
I should mention that I'm running web2py behind Apache with mod_wsgi.

Val K

unread,
Apr 7, 2020, 6:30:54 AM4/7/20
to web2py-users
Ups, sorry current is thread local and renew per request, use regular mudule

Joel Samuelsson

unread,
Apr 8, 2020, 12:43:15 AM4/8/20
to web2py-users
Thanks, this works. Is that how people usually do to keep db connections alive?

Val K

unread,
Apr 8, 2020, 1:20:27 AM4/8/20
to web2py-users
Yes, see pydal implementation https://github.com/web2py/pydal/blob/master/pydal/connection.py
It is just 176 lines
Reply all
Reply to author
Forward
0 new messages