【问题标题】:Adding request.authenticated_userid to SQLAlchemy objects in Pyramid将 request.authenticated_userid 添加到 Pyramid 中的 SQLAlchemy 对象
【发布时间】:2015-07-21 19:45:35
【问题描述】:

我正在使用此处描述的“版本化历史表”SQLAlchemy mixin:http://docs.sqlalchemy.org/en/latest/orm/examples.html#module-examples.versioned_history

效果很好,将“已更改”列添加到记录更改时间戳的历史记录表中,但我还需要记录 更改了记录(审计跟踪)。

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

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

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

【问题讨论】:

    标签: python sqlalchemy pyramid


    【解决方案1】:

    我想出了解决办法:

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

    create_version 中必须获得当前交易:

    current = transaction.get()
    

    用户在current.user 中可用。

    【讨论】:

      【解决方案2】:

      我不是 SQLAlchemy 专家,但我确实将 Pylons Pyramid 与 SLQAlchemy 一起使用,这就是我从我的事件中访问用户 ID 的方式(以下只是为了展示这个想法):

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-07
        • 1970-01-01
        • 1970-01-01
        • 2018-06-09
        • 2011-10-31
        • 2014-10-12
        • 1970-01-01
        相关资源
        最近更新 更多