Django10 Django Rest Framework(DRF)

settings

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'App',
    'App02'
]

urls

from django.contrib import admin
from django.urls import path, include


urlpatterns = [
    path('admin/', admin.site.urls),
    path('' ,include("App.urls")),
    path('book/' ,include("App02.urls")),
]

App.urls

from django.urls import path

from App import views
urlpatterns = [
    path('book//',views.BooksView.as_view(),name='book'),
]

App.views

import json

from django.http import HttpResponse, JsonResponse

from django.views.generic import View

# Create your views here.
from App.models import Bookinfo


def index(request):

    return HttpResponse("ok")

# 前后端分离,非DRF版
# 后端需要向前端提供JSON数据
class BooksView(View):
    # 查询所有图书
    def queryset_to_list(self,querset):
        res = []
        for obj in querset:
            res.append(obj.to_dict())
        return res


    def get(self,request,*args,**kwargs):
        books = Bookinfo.objects.all()
        print(books)
        # 如果参数不是字典,safe应该设置为false
        return JsonResponse(self.queryset_to_list(books),safe=False)

    # 增加图书
    def post(self,request,*args,**kwargs):
        data = request.POST.dict()
        Bookinfo.objects.create(**data)
        print(data)
        return JsonResponse({
            'code':1,
            'msg':"创建成功"
        })

    def put(self,request,bid):
        # print(bid)
        book = Bookinfo.objects.get(pk=bid)
        # book.__dict__.pop("_state")

        # 获取put传参 ,参数必须是json格式
        data = request.body.decode()
        print(data)
        # # 把json字符串转换为字典
        data = json.loads(data)
        print(data)

        # 更新对象
        book.__dict__.update(data)
        print(book.__dict__)
        book.save()
        return JsonResponse({
            'code': 1,
            'msg': "修改成功"
        })

    def delete(self,request):
        pass

App02.urls

from django.urls import path
from App02 import views


app_name = 'App02'
urlpatterns = [
    path('info/',views.BookInfoView.as_view(),name='info'),
    path('info//',views.BookInfoView.as_view(),name='info'),
    path("add/",views.BookAddView.as_view(), name='add'),
]

App.views

from rest_framework.response import Response
from rest_framework.generics import GenericAPIView

# Create your views here.
from rest_framework.views import APIView

from App.models import Bookinfo
from App02.serializers import BookSerializer


class BookInfoView(GenericAPIView):
    queryset = Bookinfo.objects.all()
    def get(self,request,bid=-1):
        # 所有图书信息
        # books = Bookinfo.objects.all()
        # 序列化:把对象或queryset直接转换为字典或者是列表套字典
        # 如果是queryset则必须将many设置为True,如果对象,则不用设置
        # bs = BookSerializer(instance=self.queryset.all(),many=True)
        # print(bs.data)
        # return Response(data=bs.data)
        if bid < 0:
            return self.find_many(request)
        return self.find_one(request,bid)

    def find_many(self,request):
        bs = BookSerializer(instance=self.queryset.all(), many=True)
        return Response(data=bs.data)
        
    def find_one(self,request,bid):
        book = self.queryset.get(bid=bid)
        bs = BookSerializer(instance=book)  # 序列化
        return Response(bs.data)


class BookAddView(APIView):
    # queryset = Bookinfo.objects.all()
    serializer_class = BookSerializer
    def post(self,request):
        # print(request.data)
        # 反序列化:字符串转换为对象
        # 把前端传过来的数据赋值给data
        bs = BookSerializer(data=request.data)
        if bs.is_valid():  # 数据验证
            print(bs.validated_data) # 获取验证数据
            bs.save()  # 保存到数据库
            return Response({'code': 1,'msg':'增加成功'})
        else:
            print(bs.errors)
            return Response({'code': 0,'msg':bs.errors})


    def put(self,request):
        print(request.data)
        return Response({'code':1})

serializers

import re

from rest_framework import serializers

# 自定义的序列化器
# class BookSerializer(serializers.Serializer):
#     bid = serializers.IntegerField()
#     btitle = serializers.CharField(max_length=100)
#     bpub_date = serializers.DateField()
#     bread = serializers.IntegerField(min_value=0)
#     bcomment = serializers.IntegerField(min_value=0)
#     bimage = serializers.CharField(max_length=300)


# 通过模型生成序列化器
from App.models import Bookinfo

# 验证函数
def check_comment(value):
    if value > 10000:
        raise serializers.ValidationError("评论数量异常")

class BookSerializer(serializers.ModelSerializer):
    bcomment = serializers.IntegerField(min_value=0,validators=[check_comment])
    class Meta:
        model = Bookinfo
        # fields = ['btitle','bread','bcomment']
        # fields = "__all__"  # 所有字段
        exclude = ['bid']  # 除去bid外,包括其他所有字段

    # 单字段验证
    def validate_bread(self,value):
        print(value,type(value))
        if int(value) < 10:
            raise serializers.ValidationError("读者人数不能小于10")
        return value
    # 多个字段验证
    def validate(self, attrs):
        print(attrs)
        if re.search(r'反政府',attrs['btitle']):
            raise serializers.ValidationError("书名不正确")
        if attrs['bread'] > 1000:
            raise serializers.ValidationError("读者数量异常")
        return attrs

App.models

from django.db import models


class Bookinfo(models.Model):
    bid = models.AutoField(primary_key=True,db_column='id')
    # 如果字段的null参数不写,默认是False,默认字段非空
    btitle = models.CharField(max_length=200)
    bpub_date = models.DateField(blank=True, null=True)
    bread = models.IntegerField()
    bcomment = models.IntegerField()
    bimage = models.CharField(max_length=200, blank=True, null=True)

    class Meta:
        db_table = 'bookinfo'


    def to_dict(self):
        return {
            'btitle':self.btitle,
            'bpub_date':self.bpub_date,
            'bread':self.bread,
            'bcomment':self.bcomment,
            'bimage':self.bimage
        }

你可能感兴趣的:(5-web,python,django)