from rest_framework.permissions import IsAuthenticated
classOrderAPIView(APIView):
authentication_classes = [JSONWebTokenAuthentication,]
permission_classes = [IsAuthenticated,]
defget(self,request,*args,**kwargs):
return Response('这是订单信息')
classUserInfoAPIView(APIView):
authentication_classes = [JSONWebTokenAuthentication,]
defget(self,request,*args,**kwargs):
return Response('UserInfoAPIView')
-第一种方案,自己写登录接口
-第二种写法,用内置,控制登录接口返回的数据格式
-jwt的配置信息中有这个属性
'JWT_RESPONSE_PAYLOAD_HANDLER':
'rest_framework_jwt.utils.jwt_response_payload_handler',
-重写jwt_response_payload_handler,配置成咱们自己的
from rest_framework.authentication import BaseAuthentication
from rest_framework_jwt.authentication import BaseJSONWebTokenAuthentication
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_jwt.utils import jwt_decode_handler
import jwt
from api import models
classMyJwtAuthentication(BaseJSONWebTokenAuthentication):
defauthenticate(self, request):
jwt_value=request.META.get('HTTP_AUTHORIZATION')
if jwt_value:
try:
payload=jwt_decode_handler(jwt_value)
except jwt.ExpiredSignature:
raise AuthenticationFailed('签名过期')
except jwt.InvalidTokenError:
raise AuthenticationFailed('用户非法')
except Exception as e:
raise AuthenticationFailed(str(e))
user=self.authenticate_credentials(payload)
return user,jwt_value
raise AuthenticationFailed('您没有携带认证信息')
{
"username":"lqz/1332323223/33@qq.com",
"password":"lqz12345"
}
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSetMixin, ViewSet
from app02 import ser
classLogin2View(ViewSet):
deflogin(self, request, *args, **kwargs):
login_ser = ser.LoginModelSerializer(data=request.data,context={'request':request})
login_ser.is_valid(raise_exception=True)
token=login_ser.context.get('token')
return Response({'status':100,'msg':'登录成功','token':token,'username':login_ser.context.get('username')})
from rest_framework import serializers
from api import models
import re
from rest_framework.exceptions import ValidationError
from rest_framework_jwt.utils import jwt_encode_handler,jwt_payload_handler
classLoginModelSerializer(serializers.ModelSerializer):
username=serializers.CharField()
classMeta:
model=models.User
fields=['username','password']
defvalidate(self, attrs):
print(self.context)
username=attrs.get('username')
password=attrs.get('password')
if re.match('^1[3-9][0-9]{9}$',username):
user=models.User.objects.filter(mobile=username).first()
elif re.match('^.+@.+$',username):
user=models.User.objects.filter(email=username).first()
else:
user=models.User.objects.filter(username=username).first()
if user:
if user.check_password(password):
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
self.context['token']=token
self.context['username']=user.username
return attrs
else:
raise ValidationError('密码错误')
else:
raise ValidationError('用户不存在')
import datetime
JWT_AUTH={
'JWT_RESPONSE_PAYLOAD_HANDLER':'app02.utils.my_jwt_response_payload_handler',
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
}
user表
permssion表
group表
user_groups表是user和group的中间表
group_permissions表是group和permssion中间表
user_user_permissions表是user和permission中间表
-缓存的位置,通过配置文件来操作(以文件为例)
-缓存的粒度:
-全站缓存
中间件
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
。。。。
'django.middleware.cache.FetchFromCacheMiddleware',
]
CACHE_MIDDLEWARE_SECONDS=10
-单页面缓存
在视图函数上加装饰器
from django.views.decorators.cache import cache_page
@cache_page(5) # 缓存5s钟
deftest_cache(request):
import time
ctime=time.time()
return render(request,'index.html',context={'ctime':ctime})
-页面局部缓存
{% load cache %}
{% cache 5 'name' %}
{{ ctime }}
{% endcache %}
- 如何使用
from django.core.cache import cache
cache.set('key',value可以是任意数据类型)
cache.get('key')
-应用场景:
-第一次查询所有图书,你通过多表联查序列化之后的数据,直接缓存起来
-后续,直接先去缓存查,如果有直接返回,没有,再去连表查,返回之前再缓存
import base64
import json
dic={'name':'lqz','age':18,'sex':'男'}
dic_str=json.dumps(dic)
ret=base64.b64encode(dic_str.encode('utf-8'))
print(ret)
ret2=base64.b64decode(ret)
print(ret2)