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
from App.models import Bookinfo
def index(request):
return HttpResponse("ok")
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)
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):
book = Bookinfo.objects.get(pk=bid)
data = request.body.decode()
print(data)
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
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):
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):
serializer_class = BookSerializer
def post(self,request):
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
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
exclude = ['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')
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
}