将request.authenticated_userid添加到Pyramid中的SQLAlchemy对象

时间:2015-02-04 18:26:54

标签: python sqlalchemy pyramid

我正在使用"版本化的历史记录表" SQLAlchemy mixin在这里描述:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.versioned_history

它运作良好,添加"已更改"记录更改时间戳的历史记录表的列,但我还需要记录更改记录(审计跟踪)。

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

大。但是如何使历史映射器(mixin的一部分)使用该值?

也就是说,除了changed列之外,我希望changed_by表中包含request.authenticated_userid_history)列。最好不要手动将其添加到历史记录表记录中。

2 个答案:

答案 0 :(得分:0)

我制定了解决方案:

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

create_version中必须得到当前的交易:

current = transaction.get()

用户可在current.user

中使用

答案 1 :(得分:0)

我不是SQLAlchemy专家,但我确实使用了Pylons Pyramid和SLQAlchemy,以及我如何从我的活动中访问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