开发者

access django session from a decorator

开发者 https://www.devze.com 2022-12-26 02:49 出处:网络
I have a decorator that I use for my views @valid_session from django.http import Http404 def valid_session(the_func):

I have a decorator that I use for my views @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, **kwa开发者_Go百科rgs):        
    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. 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.


You could pass the request (or just the session) in as a parameter to the 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号