Flask peel request in the context of the project

I would like to access the sqlite3 database from a Flask application (without using Flask-SQLAlchemy as I need fts4 functionality). I'm using blueprints in Flask and I'm not sure where to put the following functions (shamelessly copied from the answer to this question on the stack) :

def request_has_connection():
    return hasattr(flask.g, 'dbconn')

def get_request_connection():
    if not request_has_connection():
        flask.g.dbconn = sqlite3.connect(DATABASE)
        # Do something to make this connection transactional.
        # I'm not familiar enough with SQLite to know what that is.
    return flask.g.dbconn

@app.teardown_request
def close_db_connection(ex):
    if request_has_connection():
        conn = get_request_connection()
        # Rollback
        # Alternatively, you could automatically commit if ex is None
        # and rollback otherwise, but I question the wisdom 
        # of automatically committing.
        conn.close()

      

My file structure:

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

      

I want the functions request_has_connection () and get_request_connection () to be accessible from all view functions and possibly from models.py. Right now, I think they all belong to my init .py project , which currently contains:

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

      

and that my request break function will be registered as

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

      

Is it correct?

+3


source to share





All Articles