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

后端 未结 3 1839
半阙折子戏
半阙折子戏 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:40

    Use only @check_login instead of check_login() - otherwise your decorator has to return a decorate as you are doing home = check_login()(home)

    Here's 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
    

    This decorator will call execute your login function if the username field is set to "blah" and then call the original method.

提交回复
热议问题