On Wednesday, December 11, 2013 12:58:39 PM UTC-8, Jonathan Vanasco wrote:
>
>
>
> I'm using it in 3 views, in one of them, passing to other functions as a
>> parameter. In this case, need I the scoped_session?
>>
>
> the scoped_session just does some things with the thread to ensure you can
> grab a global or package variable. someone can correct me if i'm wrong --
> but it uses some similar concepts to the transaction module to ensure you
> have the right session.
>
> if you're creating a session and explicitly passing it around, it doesn't
> need to be a scoped_session. a regular sqlalchemy session will be fine.
>
>
> I create the session inside the request, you say, at the same time, I
>> can register the add_finished_callback to avoid the try/finally in the
>> view body, correct?
>>
>
> yes and no. see this example:
>
>
> http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/webob.html?highlight=add_finished_callback#cleaning-up-after-a-request
>
> in that example, the DBSession is a scoped session. if you're not using a
> scoped session, you can stash the db session onto the request and access it
> the same way.
>
>
> something like this should work....
>
> def cleanup_callback(request):
> if hasattr(request,'_my_dBSession'):
> request._my_dBSession.remove()
>
>
> class ClassBasedView():
>
> def expensive_view(self):
>
> # build out a new session
> _session_factory = orm.sessionmaker()
> request._my_dbSession = _session_factory()
> # create a cleanup for the session
> self.request.add_finished_callback( cleanup_callback )
>
> # now do stuff with the session
> try :
> except:
>
I think it might be better to have a reified property on your request
factory than to use the pattern above. Also, I think you want to call
`sessionmaker()` only once during app startup. And if you're using a
non-threadlocal session, I think you want to call `session.close()` instead
of `remove()`.
For example, you could define a property like this (note: this is just a
rough sketch of the basic idea):
def special_db_session(request):
session = request.registry['special_session_factory']()
request.add_finished_callback(lambda r: session.close())
return session
In your main() function, you'll need something like this:
def main(...):
config = Configurator(...)
...
config.registry['special_session_factory'] = sessionmaker(your,
session, configuration, args, here)
config.add_request_method(special_db_session, reify=True)
...
def some_view(request):
db_session = request.special_db_session # automatically closed
some_other_function(db_session, other, args)
...
--
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/pylons-discuss.
For more options, visit https://groups.google.com/groups/opt_out.