1 定义login schema
login_schema = { "$schema": "http://json-schema.org/draft-07/schema#", "title": "login", "type": "object", "properties": { "username": {"type": "string"}, "password": {"type": "string"} }, 'required': ['username', 'password'] }
2 自定义异常
def invalid_json(): result = { 'code': -1, 'msg': 'Invalid JSON' } return result
3 封装后端参数校验装饰器
import json from jsonschema import ValidationError, validate from django.http import JsonResponse from common.my_exception import invalid_json def json_validate(schema): def valieated_func(func): def _func(self, request, *args, **kwargs): try: validate(json.loads(request.body), schema) except ValidationError as e: return JsonResponse(invalid_json(), safe=False) else: return func(self, request, *args, **kwargs) return _func return valieated_func
4 对登录参数进行校验
class Login(View): @json_validate(login_schema) 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)