-
-
Save asyd/a7aadcf07a66035ac15d284aef10d458 to your computer and use it in GitHub Desktop.
Enforce FK constraint for SQLite with when using flask-sqlalchemy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Thank you, this solved a painful problem.
Thank's a lot
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!