login_required decorator in django

前端 未结 3 2249
遥遥无期
遥遥无期 2021-02-12 22:13

Is there any difference in using login_required decorator in urls.py and in views.py ? If I put this line:

url(r\'^add/$\', login_required(views.add_media), name         


        
相关标签:
3条回答
  • 2021-02-12 22:52

    As others have pointed out, they are indeed equivalent. Two additional things to consider if you wish to take this approach:

    1. Doing it in the urls.py divorces the login requirement from the place in the code where the thing being decorated is defined. Because of this, you (or other maintainers) may forget that the function has been decorated.

    2. Because you're applying security in the urls file, it is possible for someone to mistakenly add another URL that points to the same function, but forget to wrap the function in login_required, thus leading to a security hole.

    Hope that helps.

    0 讨论(0)
  • 2021-02-12 23:03

    In Python, a decorator is a function that takes a function as an argument, and returns a decorated function. The @login_required syntax can be translated to:

    def add_media(request):
      ...
    add_media = login_required(add_media)
    

    So if you apply the decorator manually (as in your first snippet), it should generate the same effect.

    The approach in your first snippet is useful if you want to use both the decorated and undecorated versions of your view.

    0 讨论(0)
  • 2021-02-12 23:12

    Yes, they are the same. Decorators are syntactic sugar for wrapping a function in another one. So in either case, you are wrapping login_required around views.add_media.

    0 讨论(0)
提交回复
热议问题