import datetime
import jwt
from jwt import InvalidTokenError
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from uploadfile import settings
class AuthUser(object):
'''权限验证'''
def __init__(self):
pass
@staticmethod
def create_token(self, user_id):
'''生成token'''
payload = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=1),
'userid': user_id,
}
token = jwt.encode(payload, settings.SECRET_KEY).decode()
return token
@staticmethod
def auth_token(self, token):
'''解token'''
try:
user_id = jwt.decode(token, settings.SECRET_KEY).get('user_id')
return True, user_id
except InvalidTokenError as ext:
print(ext)
return False, False
-------------------------------------------------------------------------
class BaseModelViewSet(ModelViewSet):
def retrieve(self, request, *args, **kwargs):
res = super().retrieve(request, *args, **kwargs)
return Response({
'code': 0,
'msg': '查询成功',
'results': res.data
})
def update(self, request, *args, **kwargs):
super().update(request, *args, **kwargs)
return Response({
'code': 0,
'msg': '修改成功'
})
def destroy(self, request, *args, **kwargs):
super().destroy(request, *args, **kwargs)
return Response({
'code': 0,
'msg': '删除成功'
})
import random
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from collections import OrderedDict
class MyPageNumberPagination(PageNumberPagination):
'''自定义分页'''
page_size = 10
page_size_query_param = 'size'
max_page_size = 100
def get_paginated_response(self, data):
return Response(OrderedDict([
('code', 0),
('msg', '查询成功'),
('count', self.page.paginator.count),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data)
]))
|