@login_required的多个视图 [英] @login_required for multiple views
问题描述
我将有可能超过20次。所有的人都需要用户首先进行认证。我必须把 @login_required
在每一个或是否有更好的办法?
I am going to have probably over 20 views. All of them require the user to authenticate first. Do I have to put @login_required
over each one or is there a better way?
<一个href=\"https://docs.djangoproject.com/en/1.6/topics/auth/default/#django.contrib.auth.decorators.login_required\" rel=\"nofollow\">https://docs.djangoproject.com/en/1.6/topics/auth/default/#django.contrib.auth.decorators.login_required
推荐答案
我最终使得我NPAGE app目录中的新文件名为 lockdown.py
并粘贴$从C $ C <一个href=\"http://stackoverflow.com/questions/2164069/best-way-to-make-djangos-login-required-the-default\">this解决方案:
I ended up making a new file in my npage app directory called lockdown.py
and pasted the code from this solution:
import re
from django.conf import settings
from django.contrib.auth.decorators import login_required
class RequireLoginMiddleware(object):
"""
Middleware component that wraps the login_required decorator around
matching URL patterns. To use, add the class to MIDDLEWARE_CLASSES and
define LOGIN_REQUIRED_URLS and LOGIN_REQUIRED_URLS_EXCEPTIONS in your
settings.py. For example:
------
LOGIN_REQUIRED_URLS = (
r'/topsecret/(.*)$',
)
LOGIN_REQUIRED_URLS_EXCEPTIONS = (
r'/topsecret/login(.*)$',
r'/topsecret/logout(.*)$',
)
------
LOGIN_REQUIRED_URLS is where you define URL patterns; each pattern must
be a valid regex.
LOGIN_REQUIRED_URLS_EXCEPTIONS is, conversely, where you explicitly
define any exceptions (like login and logout URLs).
"""
def __init__(self):
self.required = tuple(re.compile(url) for url in settings.LOGIN_REQUIRED_URLS)
self.exceptions = tuple(re.compile(url) for url in settings.LOGIN_REQUIRED_URLS_EXCEPTIONS)
def process_view(self, request, view_func, view_args, view_kwargs):
# No need to process URLs if user already logged in
if request.user.is_authenticated():
return None
# An exception match should immediately return None
for url in self.exceptions:
if url.match(request.path):
return None
# Requests matching a restricted URL pattern are returned
# wrapped with the login_required decorator
for url in self.required:
if url.match(request.path):
return login_required(view_func)(request, *view_args, **view_kwargs)
# Explicitly return None for all non-matching requests
return None
之后,在 settings.py
我已将此添加 MIDDLEWARE_CLASSES
...
After that in settings.py
I added this to MIDDLEWARE_CLASSES
...
MIDDLEWARE_CLASSES = (
# ...
'npage.lockdown.RequireLoginMiddleware',
)
当然,这些线向下锁定整个网站:
And of course, these lines to lock the whole site down:
LOGIN_REQUIRED_URLS = (
r'/(.*)$',
)
LOGIN_REQUIRED_URLS_EXCEPTIONS = (
r'/login(.*)$',
r'/logout(.*)$',
)
这篇关于@login_required的多个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!