06| Django REST framework+Vue 生鲜超市 ——个人中心功能开发
drf的api文档自动生成
(1) url
#drf文档,title自定义 path('docs',include_docs_urls(title='仙剑奇侠传')),
访问:http://127.0.0.1:8000/docs 就可以自动生成
(2)drf文档的优点:
- 自动生成
- 文档里可以做交互和测试
- 可以生成js,shell和python代码段
(3)代码中注释的格式:
ViewSet的格式,更多请看官方文档
class GoodsListViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin,viewsets.GenericViewSet): ''' list: 商品列表,分页,搜索,过滤,排序 retrieve: 获取商品详情 '''
(4)Description
添加字段的描述有三种方式:
- model的字段中加 help_text = '字段说明'
- serializer的字段加 help_text = '字段说明'
- filter中也可以加 help_text = '字段说明'
动态设置serializer和permission获取用户信息
因为在用户注册的时候和我们在获取用户信息使用的是不同的serializer,所以我们要在次加以动态的区分
获取用户个人信息接口
(1)用户详情的序列化
users/serializers.py
class UserDetailSerializer(serializers.ModelSerializer): """ 用户详情 """ class Meta: model = User fields = ("name", "gender", "birthday", "email","mobile")
(2)users/views.py
from .serializers import UserRegSerializer # 用户 from rest_framework import mixins from rest_framework import authentication from rest_framework_jwt.authentication import JSONWebTokenAuthentication from rest_framework_jwt.serializers import jwt_encode_handler, jwt_payload_handler from rest_framework import permissions from .serializers import UserDetailSerializer class UserViewset(CreateModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet): ''' 用户 ''' serializer_class = UserRegSerializer queryset = User.objects.all() authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication) # 在创建用户的时候返回用户名和token def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = self.perform_create(serializer) re_dict = serializer.data payload = jwt_payload_handler(user) re_dict["token"] = jwt_encode_handler(payload) re_dict["name"] = user.name if user.name else user.username headers = self.get_success_headers(serializer.data) return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers) #这里需要动态权限配置 #1.用户注册的时候不应该有权限限制 #2.当想获取用户详情信息的时候,必须登录才行 def get_permissions(self): if self.action == "retrieve": return [permissions.IsAuthenticated()] elif self.action == "create": return [] return [] #这里需要动态选择用哪个序列化方式 #1.UserRegSerializer(用户注册),只返回username和mobile,会员中心页面需要显示更多字段,所以要创建一个UserDetailSerializer #2.问题又来了,如果注册的使用userdetailSerializer,又会导致验证失败,所以需要动态的使用serializer def get_serializer_class(self): if self.action == "retrieve": return UserDetailSerializer elif self.action == "create": return UserRegSerializer return UserDetailSerializer #虽然继承了Retrieve可以获取用户详情,但是并不知道用户的id,所有要重写get_object方法 #重写get_object方法,就知道是哪个用户了 def get_object(self): return self.request.user def perform_create(self, serializer): return serializer.save()
主要添加的内容:
- 继承mixins.RetrieveModelMixin -->>获取用户信息
- 重写get_object -->>获取登录的用
- get_permissions 中通过self.action ->>动态权限分配
- get_serializer_class -->>动态序列化分配
现在就可以从数据库获取用户的信息了
用户个人信息修改
只需要多添加一个继承mixins.UpdateModelMixin就可以了
class UserViewset(CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,viewsets.GenericViewSet):
用户收藏
(1)用户收藏商品详情
user_operation/serializer.py中添加
class UserFavDetailSerializer(serializers.ModelSerializer): ''' 用户收藏详情 ''' #通过商品id获取收藏的商品,需要嵌套商品的序列化 goods = GoodsSerializer() class Meta: model = UserFav fields = ("goods", "id")
(2) user_operation/view.py
class UserFavViewset(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin): ''' 用户收藏 ''' #permission是用来做权限判断的 # IsAuthenticated:必须登录用户;IsOwnerOrReadOnly:必须是当前登录的用户 permission_classes = (IsAuthenticated,IsOwnerOrReadOnly) #auth使用来做用户认证的 authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication) #搜索的字段 lookup_field = 'goods_id' def get_queryset(self): #只能查看当前登录用户的收藏,不会获取所有用户的收藏 return UserFav.objects.filter(user=self.request.user) def get_serializer_class(self): if self.action == "list": return UserFavDetailSerializer elif self.action == "create": return UserFavSerializer return UserFavSerializer
在会员中心可以看到已收藏的商品以及详细信息,点删除,可以删除对应的商品
用户留言功能
(1)user_operation/serializers.py
from .models import UserLeavingMessage class LeavingMessageSerializer(serializers.ModelSerializer): ''' 用户留言 ''' # 获取当前登录的用户 user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) #read_only:只返回,post时候可以不用提交,format:格式化输出 add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M') class Meta: model = UserLeavingMessage fields = ("user", "message_type", "subject", "message", "file", "id" ,"add_time")
(2)user_operation/views.py
from .serializers import LeavingMessageSerializer from .models import UserLeavingMessage class LeavingMessageViewset(mixins.ListModelMixin, mixins.DestroyModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet): """ list: 获取用户留言 create: 添加留言 delete: 删除留言功能 """ permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = LeavingMessageSerializer # 只能看到自己的留言 def get_queryset(self): return UserLeavingMessage.objects.filter(user=self.request.user)
(3)配置url
# 配置用户留言的url router.register(r'messages', LeavingMessageViewset, base_name="messages")
可以获取、删除留言等功能
用户收获地址
(1)user_operation/serializers.py
from .models import UserAddress class AddressSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) add_time = serializers.DateTimeField(read_only=True, format='%Y-%m-%d %H:%M') class Meta: model = UserAddress fields = ("id", "user", "province", "city", "district", "address", "signer_name", "add_time", "signer_mobile")
(2)user_operation/views.py
如果要实现增删改查功能,只要继承ModelViewSet就可以了
from .serializers import AddressSerializer,UserAddress class AddressViewset(viewsets.ModelViewSet): """ 收货地址管理 list: 获取收货地址 create: 添加收货地址 update: 更新收货地址 delete: 删除收货地址 """ permission_classes = (IsAuthenticated, IsOwnerOrReadOnly) authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication) serializer_class = AddressSerializer def get_queryset(self): return UserAddress.objects.filter(user=self.request.user)
(3)配置url
# 配置收货地址 router.register(r'address',AddressViewset , base_name="address")