How do I write a decorator for my Django/Python view?

后端 未结 3 1820
半阙折子戏
半阙折子戏 2021-01-13 16:06

Here\'s my view. Basically, it returns different Responses based on whether it\'s logged in or not.

@check_login()
def home(request):
    if is_logged_in(req         


        
3条回答
  •  悲哀的现实
    2021-01-13 16:32

    A plain decorator is simply a function that takes a function or class and returns something else (usually the same type, but this is not required). A parametrized decorator is a function that returns a decorator.

    So, with that in mind we create a closure and return it:

    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
    

提交回复
热议问题