1. 路飞学城第一天: 知识点 使用的是序列化与反序列化的使用:
1.创建一个公共相应的Json方法:
#创建一个公共响应的类: class LuffyResponse(): def __init__(self): self.status='100' self.msg=None self.data=None @property def get_dic(self): return self.__dict__ #公共异常类 class CommonException(Exception): def __init__(self,msg): self.msg=msg
from rest_framework.response import Response from rest_framework.views import APIView from api import models from api.utils.commonutils import LuffyResponse from api.utils.commonutils import CommonException from api.luffyserializers import Courseserializers from api.luffyserializers import CoursesDetailSerializers from rest_framework.viewsets import ViewSetMixin from django.core.exceptions import ObjectDoesNotExist import uuid class LoginView(APIView): def post(self, request): response=LuffyResponse() name = request.data.get('name') pwd = request.data.get('pwd') try: user=models.UserInfo.objects.get(username=name,password=pwd) #判断用户是否存在,得到一个用户对象 token=uuid.uuid4() #通过uuid生成token类的字符串 ret=models.Token.objects.update_or_create(user=user,defaults={'key':token}) #直接保存修改原来的 response.token=token response.name=name response.msg='登录成功' except ObjectDoesNotExist as e: #完成程序的健壮性有问题直接抛出异常 response.status=101 response.msg='用户名或密码错误' except Exception as e: response.status=105 response.msg=str(e) return Response(response.get_dic)
from rest_framework import serializers from api import models class Courseserializers(serializers.ModelSerializer): class Meta: model = models.Course fields = '__all__' price = serializers.SerializerMethodField() def get_price(self, obj): price_policy = obj.price_policy.all().order_by('-price').first() return price_policy.price class PolicyPriceSerializers(serializers.ModelSerializer): class Meta: model = models.PricePolicy fields = ['price', 'valid_period', 'valid_per_display'] # valid_per_display=serializers.CharField(source='get_valid_period_display') valid_per_display = serializers.SerializerMethodField() def get_valid_per_display(self, obj): return obj.get_valid_period_display() class CoursesDetailSerializers(serializers.ModelSerializer): class Meta: model = models.CourseDetail fields = '__all__' # 取出课程的所有价格策略 policy_price_list = serializers.SerializerMethodField() def get_policy_price_list(self, obj): policy_list = obj.course.price_policy.all() # policy_ser=PolicyPriceSerializers(instance=policy_list,many=True) # return policy_ser.data return [{'id': policy.pk, 'valid_per_display': policy.get_valid_period_display(),'price':policy.price} for policy in policy_list] course_name=serializers.CharField(source='course.name') teachers=serializers.SerializerMethodField() def get_teachers(self,obj): teacher_list=obj.teachers.all() return [{'id':teacher.pk,'name':teacher.name} for teacher in teacher_list]
from rest_framework.response import Response from rest_framework.views import APIView from api import models from api.utils.commonutils import LuffyResponse from api.utils.commonutils import CommonException from api.luffyserializers import Courseserializers from api.luffyserializers import CoursesDetailSerializers from rest_framework.viewsets import ViewSetMixin from django.core.exceptions import ObjectDoesNotExist class CourseView(ViewSetMixin,APIView): def get_list(self, request, *args, **kwargs): response = LuffyResponse() try: category=int(request.GET.get('category',None)) #获取课程的类型,转换为数字形式 course_list = models.Course.objects.all() if category: course_list=course_list.filter(course_category_id=category) #过滤课程类型 course_ser = Courseserializers(instance=course_list, many=True) #开始序列化 response.data = course_ser.data #返回序列化好的数据 except Exception as e: response.status = 105 response.msg = str(e) # response.msg = '您的操作有误' return Response(response.get_dic) #单个课程详情接口 def get_detail(self, request, pk): response = LuffyResponse() try: #注意:用course_id来查询 course_detail=models.CourseDetail.objects.get(course_id=pk) course_detail_ser=CoursesDetailSerializers(instance=course_detail,many=False) response.data=course_detail_ser.data response.msg='查询成功' except ObjectDoesNotExist as e: response.status = 101 response.msg = '课程不存在' except Exception as e: response.status = 105 response.msg = str(e) # response.msg = '您的操作有误' return Response(response.get_dic)
from django.conf.urls import url from django.contrib import admin from api.views import course,login from django.views.static import serve from luffy_city import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^courses/$', course.CourseView.as_view({'get':'get_list'})), url(r'^login/$', login.LoginView.as_view()), url(r'^courses/(?P<pk>d+)', course.CourseView.as_view({'get':'get_detail'})), url(r'^media/(?P<path>.*)', serve,{'document_root':settings.MEDIA_ROOT}), ] #注意: 使用了 ViewSetMixin 模块,就需要写 as_view({'get':'get_list'}) 模式里面需要传入字典来实现