Skip to content

Instantly share code, notes, and snippets.

@copocaneta
Forked from asyd/flask-sqlite.py
Created June 2, 2021 08:35
Show Gist options
  • Save copocaneta/51ae2a2bcd3e769e47784a0a8f10125a to your computer and use it in GitHub Desktop.
Save copocaneta/51ae2a2bcd3e769e47784a0a8f10125a to your computer and use it in GitHub Desktop.
Enforce FK constraint for SQLite with when using flask-sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
def create_app(config: str=None):
app = Flask(__name__, instance_relative_config=True)
if config is None:
app.config.from_pyfile('dev.py')
else:
logger.debug('Using %s as configuration', config)
app.config.from_pyfile(config)
db.init_app(app)
# Ensure FOREIGN KEY for sqlite3
if 'sqlite' in app.config['SQLALCHEMY_DATABASE_URI']:
def _fk_pragma_on_connect(dbapi_con, con_record): # noqa
dbapi_con.execute('pragma foreign_keys=ON')
with app.app_context():
from sqlalchemy import event
event.listen(db.engine, 'connect', _fk_pragma_on_connect)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment