Using SQLAlchemy session from Flask raises “SQLite objects created in a thread can only be used in that same thread”

Taking a hint from this SO answer I searched SA docs and found out you can do this:

engine = create_engine('sqlite:////var/www/homepage/blog.db?check_same_thread=False')

scoped_session wasn’t really suitable in my case since Flask-SQLAlchemy only takes a connection string argument:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


class Config(object):
    SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db?check_same_thread=False'


db = SQLAlchemy()


def create_app():
    app.config.from_object(Config)
    app = Flask(__name__)
    db.init_app(app)
    ...

According to sqlite3.connect:

By default, check_same_thread is True and only the creating thread may
use the connection. If set False, the returned connection may be
shared across multiple threads. When using multiple threads with the
same connection writing operations should be serialized by the user to
avoid data corruption.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)