Py学习  »  问与答

关于 @login_required 装饰器的问题

走遍北京的德福小猪-weibo • 9 年前 • 4813 次点击  

我遇到的情况是:<br/> 网站必须是登陆用户才能操作网站的每个功能,但是我不想在每个方法上都加上 @login_required .<br/> 有没有什么办法使 @login_required 针对整个网站,而不是针对网站的每个功能.<br/> 也就是说不用每个方法都添加@login_required

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/854
 
4813 次点击  
文章 [ 5 ]  |  最新文章 9 年前
走遍北京的德福小猪-weibo
Reply   •   1 楼
走遍北京的德福小猪-weibo    9 年前

登陆,注册 , 注销 , 找回密码 等功能我全部放在accounts app下了。 所以注册不会检查用户是否登录了。

Ziv_Luther-weibo
Reply   •   2 楼
Ziv_Luther-weibo    9 年前

注册那个页面,怎么办?

走遍北京的德福小猪-weibo
Reply   •   3 楼
走遍北京的德福小猪-weibo    9 年前

@爱情的枪 ,我在 github看了 ,django-stronghold 不支持 django1.7的。

Tested with:
 Django 1.4.x
 Django 1.5.x
 Django 1.6.x
走遍北京的德福小猪-weibo
Reply   •   4 楼
走遍北京的德福小猪-weibo    9 年前

找到了一个方法:使用 Middleware的process_request(request)方法 , 该方法在执行view之前执行。

from django.http.response import HttpResponseRedirect
from django.core.urlresolvers import reverse
class AuthRequiredMiddleware(object):
    def process_request(self , request):
         path = request.path 
         if 'accounts' in path : 
              return None
         if not request.user.is_authenticated():
              return HttpResponseRedirect(reverse('login'))
         else :
              return None

然后在 settings.py 中将我自定义的middleware 添加到 MIDDLEWARE_CLASSES 中 。

       'common.middleware.AuthRequiredMiddleware' ,

这样,每次请求发出后,都会判断用户是否登录。

爱情的枪
Reply   •   5 楼
爱情的枪    9 年前

try this https://github.com/mgrouchy/django-stronghold