Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place to initialize DB in Flask

I'm developing app in Flask and it requires DB, so what I have is I do:

app = Flask(__name__)
@app.before_request
def init_db_connection:
  # here I connect to my DB

@app.teardown_request
def destroy_db(exception):
  # here I destroy database connection

On the development server (app.run()) this is not the best place to initialize the database I guess, because also DB will get initialized even it the request comes for the static file. In production I can have a separate web server serving static files, so it shouldn't be a problem.

But still I'm thinking if this is right way to initialize DB or it is better for example to initialize DB in Blueprint which is used in that moment? Just want to know the best practice and how you guys doing this :)

Thanks!

like image 890
Ignas Butėnas Avatar asked Aug 26 '12 12:08

Ignas Butėnas


1 Answers

That's the way that I have done it in the past and the way that is advocated in the flask documentation. I would stick with it.

https://web.archive.org/web/20120825162413/http://flask.pocoo.org/docs/tutorial/dbcon/

like image 70
Lossy Avatar answered Oct 14 '22 12:10

Lossy