django 装饰器妙用

# 装饰器妙用

## 登录校验
from utils import response
def login_auth(func):
    def wrap(request, *args, **kwargs):
        # 获取token
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            return response.failResponse('登录状态失效,请重新登陆!')

        # 检验
        try:
            res = jwt.decode(token, settings.JWT_TOKEN_KEY, algorithms=['HS256'])
        except Exception as e:
            print('error:', e)
            return response.failResponse('token令牌有误,请重新登陆!')

        # 获取登录用户
        marsid = res['marsid']
        user = User.objects.get(marsid=marsid)
        request.userInfo = user
        return func(request, *args, **kwargs)

    return wrap


## 方法校验

from utils import response
def check_method(*args):
    def check(func):
        def wrap(request):
            for method in args:
                if request.method == method.upper():
                    try:
                        return func(request)
                    except Exception as e:
                        return response.failResponse('method is error')

            return response.failResponse('method is error')
        return wrap
    return check


##  登录
@csrf_exempt
def login(request):
    if request.method != 'POST':
        return response.failResponse('请求方法异常')
    else:
        try:
            # 校验用户名和密码
            body = json.loads(request.body)
            marsid = body['marsid']
            password = body['password']
            try:
                user = User.objects.get(marsid=marsid)
            except Exception as e:
                return response.failResponse("用户不存在")

            p_m = hashlib.md5()
            p_m.update(password.encode())
            if p_m.hexdigest() != user.password:
                return response.failResponse("您输入的密码错误,请重新确认输入!")
            token = make_token(marsid)

            user_info.info('User {} login Success'.format(marsid))
            return response.responseWithData('登录成功!', {'token': token})
        except Exception as e:
            user_error.error('User login exception: {}'.format(e))
            return response.failResponse('User login exception')

## Token设计

def make_token(marsid, expire=3600 * 24):
    key = settings.JWT_TOKEN_KEY
    now_t = time.time()
    param = {
        'marsid': marsid,  # 自定义key
        'exp': now_t + expire  # 过期时间的时间戳
    }
    # 定义参数,自定义参数key,加密算法
    return jwt.encode(param, key, algorithm='HS256')

## 简单使用
@csrf_exempt
@check_method('GET')
@login_auth
def send(request):
    return response.responseWithData('msg', 'ok')

当django采用了视图类时,加上装饰器需要做特别处理
比如post方法需要csrf_exempt装饰,请求才能放行

class viewtest(View):

    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        return super(viewtest, self).dispatch(*args, **kwargs)

    def get(self):
        pass

    def post(self):
        pass
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值