Accessing django session from decorator

I have a decorator that I use for my @valid_session views

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. When the user is logged in, I put the username in my session.

+2


source to share


3 answers


Would 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

      

+4


source


The view function takes a request as its first parameter, so the decorator will receive it as its first parameter. You can only take the session out of it with request.session.



+1


source


You can pass the request (or just the session) as a parameter to the decorator . I just don't know how to get to it in order to transfer it. I was trying to figure out something similar last night.

0


source







All Articles