13

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!

Ignas Butėnas
  • 6,061
  • 5
  • 32
  • 47
  • What library are you using to connect to the database? If the library is doing connection pooling or using lazy connections it shouldn't be a problem. – Cenk Alti Jan 26 '13 at 22:37
  • Hi. I'm using psycopg2 to connect to PostgreSQL. So you suggest using `psycopg2.pool` and create connections with `getconn`? – Ignas Butėnas Jan 27 '13 at 06:47
  • 2
    Exactly. Or use SQLAlchemy on top of it. SQLAlchemy can also handle connection pooling. – Cenk Alti Jan 27 '13 at 18:42
  • Nice. Thanks for the tip. I do not want to use SQLAlchemy for now (I'm working with plain SQL queries and don't need additional complexity yet), but will start to use pooler. – Ignas Butėnas Jan 27 '13 at 18:53

0 Answers0