gpt4 book ai didi

python - 将非线程 SQLAlchemy 代码与 Flask-SQLAlchemy 集成

转载 作者:行者123 更新时间:2023-12-03 17:03:57 25 4
gpt4 key购买 nike

我有一个 python 模块 UserManager 负责所有与用户管理相关的事情——用户、组、权限、身份验证。通过在构造函数中传递 SQLAlchemy 引擎参数的主类提供对这些 Assets 的访问。需要引擎来进行表类映射(使用映射器对象)并发出 session 。

这是在 app 模块中建立 gobal 变量的方式:

class UserManager:

def __init__(self, db):
self.db = db
self._db_session = None
meta = MetaData(db)

user_table = Table(
'USR_User', meta,
Column('field1'),
Column('field3')
)
mapper(User, user_table)

@property
def db_session(self):
if self._db_session is None:
self._db_session = scoped_session(sessionmaker())
self._db_session.configure(bind=self.db)
return self._db_session

class User(object):
def init(self, um):
self.um = um

from flask.ext.sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)
um = UserManager(db.engine)

该模块本身被设计为与上下文无关,因此它既可以用于本地运行,也可以用于 Web 应用程序。

但是这里出现了问题:有时我会遇到可怕的“在回滚无效事务之前无法重新连接”错误,这可能是由于 UserManager 代码中的一些失败事务引起的。

我现在正试图找出问题的根源。在 Web 服务器的动态上下文中如何处理数据库可能不是正确的方法?也许我必须将 db.session 传递给 um 对象,这样我才能确定 db 连接没有混淆?

最佳答案

在 Web 上下文中,您应该考虑隔离每个用户的请求。为此,您必须使用 flask.g

To share data that is valid for one request only from one function to another, a global variable is not good enough because it would break in threaded environments.Flask provides you with a special object that ensures it is only valid for the active request and that will return different values for each request. In a nutshell: it does the right thing, like it does for request and session.



你可以看到更多关于 here .

关于python - 将非线程 SQLAlchemy 代码与 Flask-SQLAlchemy 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27165706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com