简体   繁体   English

从装饰器访问django会话

[英]access django session from a decorator

I have a decorator that I use for my views @valid_session 我有一个用于视图的装饰器@valid_session

from django.http import Http404

def valid_session(the_func):
"""
function to check if the user has a valid session
"""
def _decorated(*args, **kwargs):        
    if ## check if username is in the request.session:
        raise Http404('not logged in.')
    else:
        return the_func(*args, **kwargs)
return _decorated

I would like to access my session in my decoartor. 我想在我的decoartor中访问我的会话。 When user is logged in, I put the username in my session. 用户登录后,我将用户名放在会话中。

Will something like the following solve your problem: 可以通过以下方法解决您的问题:

def valid_session(func):
    def decorated(request, *args, **kwargs):
        print request.session
        return func(request, *args, **kwargs)
    return decorated

The view function takes the request as the first parameter, so the decorator will receive it as its first parameter as well. 视图函数将请求作为第一个参数,因此装饰器也将请求作为其第一个参数。 You can pull the session out of it with just request.session. 您可以仅通过request.session将会话拉出会话。

You could pass the request (or just the session) in as a parameter to the decorator . 您可以将请求(或只是会话)作为参数传递给decorator I just don't know how to get at it to pass it in. I was trying to figure out something similar last night. 我只是不知道如何通过它。昨晚我试图找出类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM