我想从Flask应用程序访问sqlite3数据库(不使用Flask-SQLAlchemy,因为我需要fts4功能)。我正在使用Flask蓝图,我不知道在哪里放置以下函数(从对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)
# 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()
我的文件结构是:
app
├── __init__.py
├── main
│ ├── forms.py
│ ├── __init__.py
│ ├── views.py
├── models.py
├── static
└── templates
├── base.html
├── index.html
└── login.html
我希望可以从所有视图函数访问request_has_connection()和get_request_connection()函数,也可以从models.py访问。现在,我认为它们都属于我的蓝图 init .py,目前包含:
from flask import Blueprint
main = Blueprint('main',__name__)
from . import views
我的请求拆解功能将被注册为
@main.teardown_request
def close_db_connection(ex):
<blah-blah-blah>
这是对的吗?