On Wednesday 08 April 2009 05:53:12 Michael Bayer wrote:
> On Apr 7, 2009, at 6:07 PM, rintin...@googlemail.com wrote:
> > Hey Everyone,
> >
> > I'm new to SQLAlchemy (used to using Django's ORM but need to switch)
> > and there's just one thing I'm struggling with, which is when am I
> > supposed to create Sessions? I am of course creating "scoped
> > sessions". I feel like a real dunce for not being able to get my head
> > around it.
> >
> > Do I create one per-request and pass it around? That just doesn't feel
> > quite right to me. Or can I create them at module-level when I need
> > them?
>
> per-request is the most natural approach.   The point of the
> "scopedsession" is that you can use it as a "global" object, there's
> no need to pass it around.  It automatically routes operations to a
> thread-local session.  I'm sure django does something similar.   the
> chapter on sessions includes a discussion on integrating scopedsession
> within a web application, you should check it out.
>
> > Also, is it okay to call commit() more than once on the same
> > session?
>
> absolutely.
>
> > On a per-function basis even (seems like an awful lot of
> > boilerplate code in each function though… surely not?!)
>
> depending on what you're doing , this may or may not be appropriate.
> boilerplate can be cut down using a decorator, such as:
>
> @commits
> def do_some_stuff(...):
>     ....
>
> the decorator:
>
> def commits(fn):
>      def go(*args, **kw):
>          try:
>              return fn(*args, **kw)
>              Session.commit()

Not to be to nitpicky... but this commit is never reached. And dangling 
transactions can be very irritating.


I'd go for this (untetsted)

def transaction(f)
      def _wrapper(*args, **kwargs):
           commit = True
           try:
                return f(*args, **kwargs)
           except:
                commit = False
           finally:
                (session.commit if commit else session.rollback)()


Diez

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to