Search code examples
pythonsqlalchemypyramid

Pyramid get current user/user id without access to request


Is there any way to access current user object or at least id without access to request? Let's say in model?

I use pyramid and SQLAlchemy.

First I thought about Singleton, but I think this may return wrong object when there is more users.

class UserSingleton(object):
    user = None

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

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

I need this to use with my model, but I can't pass request in here, because this is called by orm event:

@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

Solution

  • Ok, found a solution by doing:

    from pyramid.threadlocal import get_current_request
    request = get_current_request()