-: Hi guys and welcome back.
In this video, we're going to do something similar
to what we did in the last one,
but for cursors in our database.py.
Because we've got a bit of duplication here.
So let's get to it.
Every function here has these two contextmanagers.
We could make it into one contextmanager if we want.
So how are we gonna do that?
Is first of all, by creating the contextmanager
that I'm gonna call, get cursor.
And this one is gonna take in a connection.
And what it's gonna do,
is gonna do with connection
and then with connection.cursor as cursor,
is gonna yield the cursor.
This is gonna get decorated with the @contextmanager
as well, and we have to import it.
So we're doing that.
Notice that all that does is from contextlib
input contextmanager at the top.
Now, what we can do is instead of doing all of this,
we can do with get cursor of connection as cursor,
and that does that.
Totally up to you whether you wanna do this or not,
we don't need a try finally here
because these contextmanagers
already clean up after themselves.
So just yielding the cursor means
that we're gonna get to here with the cursor,
return it here so we can run this
and then it's gonna go back up here
and close these contextmanagers as well.
So if you wanna do this, for simplification,
then by all means, go for it.
I'm gonna apply this to all my other functions as well.
So I've gone ahead and applied get cursor
to all of these functions.
One of the great things about this
is you don't necessarily
have to put get cursor here in database.py.
You could put get cursor into the connection pool file here,
instead of get connection,
then all your functions here or your methods
could use a cursor directly passing it into database.py.
It's up to you
whether you wanna be passing cursors or connections.
If you only have one connection
that you create at the start of the application,
you could then simply use cursors every time,
and in a single connection application
that doesn't use connection pooling.
That is probably going to be faster.
So it's up to you whether you wanna do that,
but here we're worrying more about future scalability
by using connection pooling.
If you wanted to use a single connection
and not worry about multiple connections,
then you could put this inside connection pool
or rather maybe cursors or something like that,
this file could be called,
and be passing cursors around instead of connections.
But the aim of these two changes
were to teach you about simplifying your code
using these contextmanagers and how you can do that.
So hopefully this has been useful.
I hope you've learned something.
Thank you for watching and I'll see you in the next video.