金字塔获取当前 user/user id 无法访问请求

Pyramid get current user/user id without access to request

有什么方法可以访问当前用户对象或至少访问 id 而无需访问请求?让我们说在模型中?

我使用金字塔和 SQLAlchemy。

首先我想到了单例,但我认为当用户较多时这可能return错误的对象。

class UserSingleton(object):
    user = None

    def __new__(cls, user=None):
        UserSingleton.user = user
        return UserSingleton.user

    @classmethod
    def get(cls):
        return cls.user

我需要这个与我的模型一起使用,但我不能在这里传递请求,因为这是由 orm 事件调用的:

@classmethod
def log(cls, description, log_type=None, name=None):
    user = ??
    audit_log = cls(
        user_id=user.id if user else None,
        description=description,
        type=log_type,
        name=name
    )

    DBSession.add(audit_log)

    return audit_log

好的,通过以下方式找到解决方案:

from pyramid.threadlocal import get_current_request
request = get_current_request()