How to write a decorator for my Django / Python view?

Here is my view. Basically, it returns different answers based on whether they are logged in or not.

@check_login()
def home(request):
    if is_logged_in(request): 
        return x
    else:
        return y

Here is my decorator code. I just want to check if the request has headers, and if so, write it down.

#decorator to log the user in if there are headers
def check_login():
    def check_dec(func):
        if request.META['username'] == "blah":
            login(request, user)

    return check_dec

The problem is that I do not know how to write the correct decorator in this case !!! What are the arguments? What are the features? How?

+3
source share
3 answers

Use only @check_logininstead check_login()- otherwise your decorator should return the decoration as you dohome = check_login()(home)

Here is an example decorator:

def check_login(method):
    @functools.wraps(method)
    def wrapper(request, *args, **kwargs):
        if request.META['username'] == "blah"
            login(request, user) # where does user come from?!
        return method(request, *args, **kwargs)
    return wrapper

, username "blah", .

+11

- , - ( , ). - , .

, , :

def check_login(func):
  def inner(request, *args, **kwargs):
    if request.META['username'] == 'blah':
      login(request, user) # I have no idea where user comes from
    func(request, *args, **kwargs)
  return inner
+3

, , , . .

https://github.com/mzupan/django-decorators/blob/master/auth.py

@group_required(["group1", "group2"])
def show_index(request):
    view_code_here

group1 group2, 404

+2

All Articles