添加request.authenticated_用户标识到金字塔中的SQLAlchemy对象

2024-05-13 08:32:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是“versioned history table”SQLAlchemy mixin,描述如下:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.versioned_history

它工作得很好,向记录更改时间戳的history表添加了“changed”列,但我还需要记录谁更改了记录(审计跟踪)。在

在金字塔中,如果使用金字塔中可用的典型身份验证和授权子系统,request.authenticated_userid中通常可用。在

太好了。但是如何让历史映射器(mixin的一部分)利用这个值呢?在

也就是说,除了changed列之外,我希望changed_byrequest.authenticated_userid)列在_history表中。最好不要手动将其添加到历史表记录中。在


Tags: httpdocssqlalchemyrequest记录table历史mixin
2条回答

我想出了解决办法:

history_meta.py包含为before_flushSQLAlchemy事件注册的create_version函数(由mixin中定义的versioned_session)注册。在

create_version中,必须获取当前事务:

current = transaction.get()

用户在current.user中可用。在

我不是SQLAlchemy专家,但我确实在SLQAlchemy中使用了Pylons Pyramid,这就是我从活动中访问userid的方式(下面只是为了展示这个想法):

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import (
    scoped_session,
    sessionmaker,
    )

from zope.sqlalchemy import ZopeTransactionExtension
from pyramid.threadlocal import get_current_request

DBSession = scoped_session(
    sessionmaker(extension=ZopeTransactionExtension()),
    scopefunc=get_current_request)

Base = declarative_base()

# Define your tables

@event.listens_for(Base, "after_insert", propagate=True)
def user_after_insert(mapper, connection, target):
    try:
        user_id = DBSession.registry.scopefunc().userid
    except AttributeError:
        # most likely initializedb script is being called

相关问题 更多 >