SQLAlchemy: who is in charge of the "session"? (and how to test with sessions)
I need guidance on how to use objects session
with SQLAlchemy, and how to organize the unit tests of my mapped objects.
What I would like to do is something like this:
thing = BigThing() # mapped object
child = thing.new_child() # create and return a related object
thing.save() # will also save the child object
To achieve this, I thought about BigThing
actually adding myself (and these are children) to the database - but maybe that's not a good idea?
One of the reasons for adding objects as soon as possible is the Automatic values id
that are assigned by the database - the sooner they are available, the less problems (right?)
What's the best way to manage objects session
? Who is responsible for session
?
Should it only be created when needed? or kept for a long time?
What about unit tests for my mapped objects? ... how should I handle it session
? Is it good for objects with mapping to just automatically add themselves to the database? or will it lead to trouble?
source to share
A session is like a field where you store objects. Of course, you can write a method __init__
to automatically add an object to it, but that means some global (single) session exists. I'm sure this will cause problems in many cases, but it will also simplify the writing code. This is an explicit or implicit dilemma. Some people follow the Zen of Python and some don't. I prefer to specify the storage box explicitly.
Note that there is no need to add children to the session explicitly, as far as it relates to an object already in the session through a relationship. This is what the cascading rules are . By default 'save-update'
, it does exactly what you ask. You may also be interested in 'all, delete-orphan'
implementing "private" objects that should be removed along with their parent.
I see some problems for the implementation of the method save()
. There is no way to say "save these objects" in SQLAlchemy in the current version. There used to be such an opportunity, but it was never reliable. Session.flush()
(he called from Session.commit()
) dumps all changes to the database. This is probably the most annoying feature of SQLAlchemy that prevents me from using it in certain projects.
Unit testing is very easy (at least when you specify the session explicitly), see the sample code in another question .
source to share