Première méthode : utiliser l'objet spécial g de http://flask.pocoo.org/docs/tutorial/dbcon/ y http://flask.pocoo.org/docs/patterns/sqlite3/
import sqlite3
from flask import g
DATABASE = '/path/to/database.db'
def connect_db():
return sqlite3.connect(DATABASE)
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
if hasattr(g, 'db'):
g.db.close()
Deuxième méthode : utiliser la mystérieuse _app_ctx_stack de https://github.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py
from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash, _app_ctx_stack
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
top = _app_ctx_stack.top
if not hasattr(top, 'sqlite_db'):
top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
return top.sqlite_db
@app.teardown_appcontext
def close_db_connection(exception):
"""Closes the database again at the end of the request."""
top = _app_ctx_stack.top
if hasattr(top, 'sqlite_db'):
top.sqlite_db.close()
Quelle méthode est la meilleure ? Quelle est la différence ?
1 votes
Relié, mais sans explication non plus : flask.pocoo.org/docs/extensiondev