Skip to content

Instantly share code, notes, and snippets.

@asyd
Forked from lucidfrontier45/flask-sqlite.py
Last active May 16, 2023 21:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save asyd/a7aadcf07a66035ac15d284aef10d458 to your computer and use it in GitHub Desktop.
Save asyd/a7aadcf07a66035ac15d284aef10d458 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)
@copocaneta
Copy link

Thanks!

@ggsdc
Copy link

ggsdc commented Nov 10, 2021

Thank you, this solved a painful problem.

@VanderSVan
Copy link

Thank's a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment