Python for Entrepreneurs Transcripts
Chapter: Accessing databases from Python: SQLAlchemy ORM
Lecture: Demo: Creating the Unit of Work
0:02 Now that we have our schema created, let's actually query some data. Now, in order to either insert, update, delete, or query data, we're going to
0:12 need to talk about this DbSessionFactory and the unit of work pattern. The way SQLAlchemy works, we've already said, is
0:19 to use the unit of work design pattern and what that means is you begin a unit of work, you make a bunch of
0:24 changes, inserts, updates and deletes and then when you are finally done you can either abandon the unit of work or you can commit it.
0:33 The final step here is to actually create the thing that manages this unit of work for us.
0:38 OK, so if we look up here, we are going to need to import sqlalchemy.orm and down here we're going to create, I am going to say
0:48 sqlalchmey.orm.sessionmaker, kind of like declarative base. This factory method here is going to create this thing that will itself be
0:57 a callable function that can make these unit of works. So we are going to need to store it somewhere, I'll call it a session_factory
1:06 and so we are just going to do store it here, we'll say DbSessionFactory.session_factory the name maybe gives away, let's just call it factory, right,
1:19 because there is too many sessions in here. And let's go ahead and set that to be None initially,
1:25 and then we'll do a test, remember, I said we want one and only one engine so we are going to bind the engine here,
1:31 so this tells the factory basically how to tie itself back to the database and the base classes and all these things.
1:40 And again, we don't want to actually run this method over and over, we run it two times, we get two engines, that would be bad,
1:47 so let's do a little test here, so we'll say if this is already created, we're just going to return, there is nothing to do, OK? And in this sense,
1:56 we're only going to be able to ever create one of these engines per connection,
1:59 in this case we're just doing one, so here we go, this is going to be great. Now we're ready to basically call this like this, so we want a session,
2:08 we'll not do this here really but this is what we're going to do.