Django自己写一个认证decorator

本文介绍了一种使用Python实现的认证装饰器方法,该方法应用于Web应用程序中以验证用户身份。文章通过具体的类装饰器和函数装饰器展示了如何限制对特定视图函数的访问,仅允许已登录用户访问。
# 认证装饰器
class AuthDecorator(object):
    @method_decorator(login_required(login_url="/login/"))
    def dispatch(self, request, *args, **kwargs):
        return super(AuthDecorator, self).dispatch(request, *args, **kwargs)


def has_auth(func):
    def auth(request, *args, **kwargs):
            if not request.session.get("username"):
                return redirect(reverse("login"))
            return func(request, *args, **kwargs)
    return auth


@has_auth
def index(request):
    user = request.session.get("username")
    business_obj = Business.objects.all()
    user_obj = User.objects.all()
    hosts = Host.objects.filter(user__username=user)
    return render(request, "index.html", {
        "hosts": hosts,
        "business_obj": business_obj,
        "user_obj": user_obj
    })
复制代码

 

类装饰器

复制代码
# 认证装饰器
class Auth(View):
    def dispatch(self, request, *args, **kwargs):
        user_obj = UserInfo.objects.filter(username=request.session.get("username")).first()
        if not user_obj:
            return redirect(reverse("login"))
        return super(Auth, self).dispatch(request, *args, **kwargs)


# 主页视图
class IndexView(Auth):
    def get(self, request):
        user = request.session.get("username")
        business_obj = Business.objects.all()
        user_obj = UserInfo.objects.all()
        hosts = Host.objects.filter(user__username=user)
        return render(request, "index.html", {
            "hosts": hosts,
            "business_obj": business_obj,
            "user_obj": user_obj
        })
复制代码

转载于:https://www.cnblogs.com/hjm-hjm/p/8831427.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值