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

Ben Hedgepeth
seal-mask
.a{fill-rule:evenodd;}techdegree
Ben Hedgepeth
Python Web Development Techdegree Student 10,287 Points

Flask 'g' object

Before each request a connection needs to be made to the database. However I'm not seeing any explanation as to why g is being used to setup that very connection? What is the advantage of doing this?

Couldn't the following code be equally as sufficient: models.database.connect()?

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

You want your code to be as "thread-safe" as possible then the g object is your best guarantee that you can maintain your database connection and not have to continually open and close your connection to the database.

Kenneth shows a good way to do this using the "@before_request" as being a good place to open the connection and the "@after_request" where you should tear-down (close) the connection. But this can be inefficient since opening and closing the database connection is time-consuming.

A more efficient way is to use a helper function which checks if the connection is currently being held in the g object.

Read this--

http://flask.pocoo.org/docs/0.12/tutorial/dbcon/