>
> 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()
except:
Session.rollback()
raise
return go
Session is a scopedsession which can be declared at the module level.
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
Darn.. you're right of course :)
Diez