我的项目后端是python-flask框架,使用了flask-restx来开发RESTful API。
前几天遇到一个问题:想要在restx的某个命名空间中调用多线程来批量提交数据库。但是报错了,显示需要使用 with app.app_context() 来设置一个上下文。
但是我的项目采用工程模式创建flask app实例。并且在使用了 flask-restx 命名空间的情况下,如果模块需要调用with app.app_context()是无法实现的。会触发循环导入。
推荐使用SQLAlchemy的 scoped_session 来创建一个线程安全的会话:
from sqlalchemy import create_engine
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase, sessionmaker, scoped_session
# 定义基类
class Base(DeclarativeBase):
pass
# 创建数据库引擎
engine = create_engine() # 数据库的连接配置
# 创建线程安全的会话
db_session = scoped_session(sessionmaker(bind=engine))
# 初始化 SQLAlchemy
db