Refactor Sessions to clarify their usage#366
Conversation
DBSession has been renamed to HandlerSession. The following exist now: - HandlerSession: a DB session scoped to the current handler; should therefore only be used inside handlers. - ThreadSession: a DB session scoped to the current thread; should be used outside of handlers, e.g. when firing off tasks in threads, or inside of services. A special HandlerSession, with knowledge of the current user, and that verifies permissions on commit, is available as `self.Session` on the base handler. This is the *preferred way of accessing* HandlerSession. To make it easier to get hold of the current engine, the Sessions each have a `.engine` attribute: `HandlerSession.engine`. This avoids having to access the engine as `HandlerSession.session_factory.kw["bind"]`.
1bcea32 to
3fdfdda
Compare
|
@Theodlz Just to confirm that we decided not to take this route, so there are no ideas from this PR that need to be saved? |
|
@stefanv so some ideas could be salvaged. The way I ended up doing this in skyportal, is by having some function where I change the context id to be some unique randomized value, before using the session (I think I use some decorator for this). That way the session doesn't expect a context id set by the request ID of tornado, and it's unique for that one process/function. So in theory we could have something similar, some context manager that yields a function that is thread scoped rather than tornado request id scoped. It's not a priority though, since we got that to work in SkyPortal. But would be nice to have some standardized method for this in baselayer at some point. Here's what I added in baselayer if you want to take a look (for context, this was added to handle running some functions async, which didn't work before since the session created in the async call seemed to still have the context id of the main thread, i.e. it was the same session and when the handler returned it closed it which killed it in the async function call. rescoping the context id in the async function call fixed this): https://github.com/skyportal/skyportal/blob/main/skyportal/utils/asynchronous.py |
DBSession has been renamed to HandlerSession.
The following exist now:
A special HandlerSession, with knowledge of the current user, and that verifies permissions on commit, is available as
self.Sessionon the base handler. This is the preferred way of accessing HandlerSession.To make it easier to get hold of the current engine, the Sessions each have a
.engineattribute:HandlerSession.engine.This avoids having to access the engine as
HandlerSession.session_factory.kw["bind"].