python - Flask teardown request in context of blueprint -


i access sqlite3 database flask application (without using flask-sqlalchemy, since require fts4 functionality). using flask blueprints, , not sure put following functions (shamelessly copied response this stackoverflow question):

def request_has_connection():     return hasattr(flask.g, 'dbconn')  def get_request_connection():     if not request_has_connection():         flask.g.dbconn = sqlite3.connect(database)         # make connection transactional.         # i'm not familiar enough sqlite know is.     return flask.g.dbconn  @app.teardown_request def close_db_connection(ex):     if request_has_connection():         conn = get_request_connection()         # rollback         # alternatively, automatically commit if ex none         # , rollback otherwise, question wisdom          # of automatically committing.         conn.close() 

my file structure is:

app ├── __init__.py ├── main │   ├── forms.py │   ├── __init__.py │   ├── views.py ├── models.py ├── static └── templates     ├── base.html     ├── index.html     └── login.html 

i want request_has_connection() , get_request_connection() functions accessible view functions , maybe models.py well. right now, i'm thinking belong in blueprint init.py, contains:

from flask import blueprint main = blueprint('main',__name__) . import views 

and request teardown function registered as

@main.teardown_request def close_db_connection(ex):     <blah-blah-blah> 

is right?


Comments