Building data-driven web apps with Flask and SQLAlchemy Transcripts
Chapter: Using SQLAchemy
Lecture: Adding type hints to the session factory
0:00 I guess, real, real quick, let's
0:01 make this a little bit nicer.
0:04 I don't like that this doesn't give
0:06 us much information about what comes out of it
0:08 and it's not super easy to get that
0:11 to happen, so let's do this.
0:12 Let's define a function called create_session().
0:14 That's more obvious.
0:15 And it's going to return a session object
0:18 that comes from sqlalchemy.orm
0:22 and for now it's just going to say
0:23 return __factory(), like this.
0:27 Let's tell it that this is global, like that.
0:33 Okay, this is pretty good.
0:34 But of course when we now go to db_session. Uou still see it.
0:38 You still see it at the top and I'd kind of like that
0:41 to not be the case so let's refactor rename this
0:45 to double underscore and you see it renamed it everywhere.
0:49 And now, is it gone? Ah, yeah.
0:52 We just have create_session and global_init.
0:56 So where are we doing this factory
0:57 we don't need any of this stuff anymore.
1:00 That can all be gone, we just say
1:01 = DBsession.createsession
1:05 the type annotation on the return value there
1:07 should be enough so that when we say session.
1:09 Boom, there it all is. Okay, that's it.
1:15 We're all good to go.
1:16 We clear the session, we make the changes
1:18 we call commit, beautiful.