# 装饰器妙用
## 登录校验
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