简体   繁体   English

Flask-sqlalchemy 临时会话/上下文变量

[英]Flask-sqlalchemy temporary session/context variable

I'm exposing an API that allows users to do various CRUD operations.我公开了一个 API 允许用户进行各种 CRUD 操作。

The underlying classes of my SQLAlchemy data model are derived from a single declarative base, which include a "insert_uuid" field that (as the name implies) should register the UUID of the user triggering every insert.我的 SQLAlchemy 数据 model 的底层类派生自单个声明性基础,其中包括一个“insert_uuid”字段(顾名思义)应该注册触发每次插入的用户的 UUID。

In every API call, I'd like to set a 'temporary' session/context/whatever variable that I can use to set a default value.在每个 API 调用中,我想设置一个“临时”会话/上下文/任何可用于设置默认值的变量。 However, without having to rely on Flask's request module, because this declarative base resides in a 'data package' that does not need Flask in any way.但是,不必依赖 Flask 的请求模块,因为这个声明性基础驻留在一个“数据包”中,无论如何都不需要 Flask。

Ie something like:即是这样的:

db.session.set_variable(user-uuid='aaaa-bbbb-etc')
db.session.add(object1)
db.session.add(object2)
db.session.add(object3)
db.session.remove_variable(user-uuid)

I've looked at setting the execution option on the SQLAlchemy engine.我看过在 SQLAlchemy 引擎上设置执行选项。 However this is an immutable dict, initialized upon creating the engine.然而,这是一个不可变的字典,在创建引擎时初始化。

def get_user_uuid(context):
    return context.engine.get_execution_options().get('user_uuid', None)

class BaseTableDefinition(object):
    insert_uuid = Column("insert_uuid", UUIDType(), default=get_user_uuid)
    ....

BaseTable = declarative_base(cls=BaseTableDefinition)

And then, upon initializing the engine:然后,在初始化引擎时:

engine = create_engine(self._cn_string, echo=False, execution_options={'user_uuid': 'aaaa-bbbb-etc'})

In a 'static' back-end with a single-user-per-engine setup this could work, but it does not for my API use case.在具有单个用户每个引擎设置的“静态”后端中,这可能有效,但不适用于我的 API 用例。

What's the best way to achieve the above in a flask-sqlalchemy context, ideally relying on some functionality of the underlying SQLAlchemy core?在 flask-sqlalchemy 上下文中实现上述目标的最佳方法是什么,最好依赖底层 SQLAlchemy 核心的某些功能?

Thanks!谢谢!

SQLAlchemy sessions have an info attribute, a user-modifiable dictionary, so something like this would work: SQLAlchemy 会话有一个信息属性,一个用户可修改的字典,所以像这样的东西会起作用:

db.session.info['user-uuid'] = 'aaaa-bbbb-etc'
db.session.add(object1)
db.session.add(object2)
db.session.add(object3)
db.session.info.pop('user-uuid')

Session and sessionmaker accept an info keyword argument to set the contents of the dictionary at creation time. Sessionsessionmaker接受一个info关键字参数以在创建时设置字典的内容。 To set the value dynamically at session creation time in Flask-SQLAlchemy you might want to subclass SQLALchemy and override / extend create_session or create_scoped_session .要在 Flask-SQLAlchemy 中的创建时间 session 动态设置该值,您可能需要继承 SQLALchemy并覆盖/扩展create_sessioncreate_scoped_session

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM