Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Build a Social Network with Flask Takin' Names Before and After Requests

Pete Jeffryes
Pete Jeffryes
5,752 Points

What if we didn't use the global decorator?

I do not completely understand the global decorator. Is it helping to open the database from any view? What if we didn't use it? Would we just have to type out more code or there more function than just saving some lines of code? Thanks.

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

You'd have to connect to the database, then use the database, then close the database connection, every time you needed the database. So, yeah, it's mostly about saving lines of code (and repetition) but it's also about making it require less headspace to keep up with what's going on.

Why wouldn't you want to create your own global var with the database so you would only have to open the database once? like:

https://gist.github.com/anonymous/9d7403a369bef4a57e2f

Wouldn't this work as well and save loads of time for the user because we're not opening and closing the database connection every time?

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

That might work well for some smaller apps but, the way I understand it, having that long running, open connection can lead to time outs, memory bloating, and maybe getting locked out of your database if it had some sort of time-based security. It is extra work opening and closing the connection on every request, but a) that's the recommended approach according to the Peewee docs; and b) that guarantees a fresh, clean connection each time you might need one.

I understand that keeping the connection open is not recommended. But why are we SETTING the g.db to models.DATABASE before every request? Why not set it once outside the view and than use the global variable g.db to connect/disconnect from database?