librelist archives

« back to archive

Storing in app-context space?

Storing in app-context space?

From:
David Oberst
Date:
2013-04-27 @ 17:16
I'm looking at Flask to power a small, in-house website which talks to a
database using SQLAlchemy.  The SQLAlchemy code already exists as part of
other stuff, one reason I won't be using the Flask-SQLAlchemy extension. 
Another is that the usage is a little weird, accessing one of a number of
databases with identical structures depending on which "project" the
request is for.

Where Flask-SQLAlchemy uses a single scoped session, I was going to use a
dictionary of them, one for each project, setting some sort of index
variable based on the project as I determine it at the start of the
request.  Ideally something like this:

myScopedSessions = {'prj1': ..., 'prj2': ...} # or however I create my
scoped sessions, one-time
...
# in some sort of before_request routine
g.dbSessionIndex = determineProjectFromRequest()  # would be "prj1" or
similar
g.dbSession = myScopedSessions[g.dbSessionIndex] # an addressing convenience
# I can now use g.dbSession wherever I need the SQLA session for the request
...
# in a teardown_appcontext handler
g.dbSession.remove()    # aka myScopedSessions[g.dbSessionIndex].remove()

It looks like this would work for the unreleased 0.10 changes, since "g"
will survive to the app context teardown, but not in 0.9 since "g" will
already have been destroyed in the request teardown?  I'd need someplace
else thread-safe to stash my "dbSessionIndex"?  It looks like I could
subclass AppContext to add a variable of my own there, subclass Flask to
replace app_context to return an instance of my AppContext subclass, and
do a similar LocalProxy type of thing for it the way globals.py sets up
"g" in 0.10.  I've mainly just been reading the docs so far - does this
seem a reasonable way to get app-context storage in 0.9, or is there
something already provided I've missed?

Also, is there any ballpark date for a 0.10 release package?