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

前端 未结 2 1472
面向向阳花
面向向阳花 2020-12-05 18:21

I have a Flask view which uses SQLAlchemy to query and display some blog posts. I am running my app using mod_wsgi. This view works the first time I go to the page, but re

2条回答
  •  不知归路
    2020-12-05 18:29

    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.

提交回复
热议问题