9 django CBV

1 修改views

import hashlib
import json

from django.core import serializers
from django.http import JsonResponse
from django.utils.decorators import method_decorator


# Create your views here.
from django.views import View

from user.models import User
from utils.mytoken import make_token, login_check

class Login(View):
    def post(self, request):
        json_obj = json.loads(request.body)  # 转字典
        try:
            username = json_obj['username']
            password = json_obj['password']
        except Exception as e:
            result = {'code': -1, 'msg': u'用户名或密码为空!'}
            return JsonResponse(result)

        users = User.objects.filter(username=username)  # 返回数组
        if users is None:
            result = {'code': -1, 'msg': u'用户名或密码错误!'}
            return JsonResponse(result)
        user = users[0]
        m = hashlib.md5()
        m.update(password.encode())
        # 密码比对
        if m.hexdigest() != user.password:
            result = {'code': -1, 'msg': u'用户名或密码错误!'}
            return JsonResponse(result)

        # 生成 token
        token = make_token(username)
        # encode的作用是将unicode编码的字符串编码成二进制数据
        # decode的作用是将二进制数据解码成unicode编码
        result = {'code': 1, 'data': {'token': token}, 'msg': u'登录成功!'}
        return JsonResponse(result)


class List(View):
    @login_check
    def get(self, request):
        all_users = serializers.serialize("json", User.objects.all())
        result = {'code': 1, 'data':{'all_users':all_users}, 'msg': u'获取所有用户成功!'}
        return JsonResponse(result)

 

2 修改工程urls

urlpatterns = [
    path('admin/', admin.site.urls),
    path('v1/user/', include(('user.urls','user'), 'user')),  # 分布式路由,匹配到/v1/user后,到 user urls中找 user 后面的path

]

 

3 修改user urls

urlpatterns = [
    path('login', Login.as_view(), name='login'),
    path('list', List.as_view(), name='list'),
]

 

4 修改login_check方法

# token 验证装饰器
def login_check(func):
    def wrapper(self, request, *args, **kwargs):

        # token 校验
        token = request.META.get('HTTP_AUTHORIZATION')
        # 没有 token
        # if not a 用来判断变量 a 是否 None,等于 if a is not None
        if token is None:
            result = {'code':403, 'msg':u'用户未登录 - 没有权限!'}
            return JsonResponse(result)
        try:
            res =jwt.decode(token, settings.LIZI_TOKEN_KEY, algorithms='HS256')
        except Exception as e:
            print('jwt error {}'.format(e))
            result = {'code':403, 'msg': u'用户未登录!'}
            return JsonResponse(result)

        username = res['username']
        user = User.objects.get(username=username)
        # user 挂载 request 上,以便后面方法可以直接取出用户
        request.myuser = user

        return func(self, request, *args, **kwargs)
    return wrapper

 

上一篇:Django学习小记-CBV


下一篇:07 flask视图类 CBV