需求
构建用户系统
构建博客系统
1.只有登录的用户才可以创建博客
2.博客创建自动绑定登录用户
setting.py
CACHES = {
'default':{
'BACKEND':'django_redis.cache.RedisCache',#指定缓存类型 redis缓存
'LOCATION':'redis://127.0.0.1:6379/1', #缓存地址
}
}
1.创建models.py
from django.db import models
class User(models.Model):
u_name = models.CharField(max_length=32, unique=True)
u_password = models.CharField(max_length=256)
def check_password(self, password):
return self.u_password == password
class Blog(models.Model):
b_title = models.CharField(max_length=128)
b_content = models.TextField()
2.创建serializer
serializers.py
from rest_framework import serializers
from App.models import User, Blog
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ("id", "u_name", "u_password")
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Blog
fields = ("id", "b_title", "b_content")
3.views.py
因为登录和注册都是post请求,为了区分不同的,需要重写post方法,进行注册
request.query_params.get() GET请求获取参数
request.data.get() post请求参数
通过参数action是login还是register,来判断是登录还是注册,如果是注册直接return,
如果是登录:知识点
1.通过request.data.get()拿到数据
2.判断是否存在exists()
3.验证密码
4.存在利用uuid生成token
5.将token作为key存到cache中,value是user.id
6.Django REST的APIException异常处理,参数detail,code=statu.Htpp.....
import uuid
from django.core.cache import cache
from rest_framework import status
from rest_framework.exceptions import APIException
from rest_framework.generics import CreateAPIView, ListCreateAPIView
from rest_framework.response import Response
from App.models import User, Blog
from App.serializers import UserSerializer, BlogSerializer
class UsersAPIView(CreateAPIView):
serializer_class = UserSerializer
queryset = User.objects.all()
# 重写post,为了区分登录和注册
def post(self, request, *args, **kwargs):
# request.query_params.get() 这是RESTFul 的GET请求方法
action = request.query_params.get("action")
if action == "register":
return self.create(request, *args, **kwargs)
elif action == "login":
u_name = request.data.get("u_name")
u_password = request.data.get("u_password")
users = User.objects.filter(u_name=u_name)
if not users.exists():
raise APIException(detail="用户不存在", code=status.HTTP_400_BAD_REQUEST)
user = users.first()
if not user.check_password(u_password):
raise APIException(detail="密码错误", code=status.HTTP_400_BAD_REQUEST)
token = uuid.uuid4().hex
print(type(cache))
cache.set(token, user.id, 60*60*24)
data = {
"msg": "ok",
"status": status.HTTP_200_OK,
"token": token
}
return Response(data)
else:
raise APIException(detail="请提供正确的action", code=status.HTTP_400_BAD_REQUEST)
继承ListCreateAPIView创建和获取
获取需要重写get方法
利用request.query_params.get('token')拿到token
利用token(key)拿到cache对应的user.id(value)
通过id拿到用户信息User.object.get(token)
post里还需要通过token获取用户
自己封装的方法是没有request的
封装一个方法,request可通过self那到,self.request.query_params/data
class BlogsAPIView(ListCreateAPIView):
serializer_class = BlogSerializer
queryset = Blog.objects.all()
def get_user(self):
try:
token = self.request.query_params.get("token")
user_id = cache.get(token)
user = User.objects.get(pk=user_id)
except Exception as e:
print(e)
raise APIException(detail="用户信息不存在", code=status.HTTP_404_NOT_FOUND)
return user
def get(self, request, *args, **kwargs):
user = self.get_user()
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
user = self.get_user()
return self.create(request, *args, **kwargs)
urls.py
from django.conf.urls import url
from App import views
urlpatterns = [
url(r'^users/', views.UsersAPIView.as_view()),
url(r'^blogs/', views.BlogsAPIView.as_view()),
]