Django-DRF-图书增删改查 !!!
自己封装的
class MyResponse():
def __init__(self):
self.status = 100
self.msg = None @property
def get_dic(self):
return self.__dict__ # 自己封装的
# class List():
# def get_list(self, request):
# response = MyResponse()
# book_list = self.model.objects.all()
# book_ser = self.serializer(instance=book_list, many=True)
# print(book_ser.data)
# response.books = book_ser.data
# return Response(response.get_dic)
#
#
# class ObjSave():
# def save(self, request):
# response = MyResponse()
# book_ser = self.serializer(data=request.data)
# if book_ser.is_valid():
# book_ser.save()
# else:
# response.status = 101
# response.msg = book_ser.errors
# return Response(response.get_dic)
#
#
# class Books(List, ObjSave, APIView):
# model = models.Book
# serializer = BookSerializer
#
# def get(self, request):
# return self.get_list(request)
#
# def post(self, request):
# return self.save(request)
#
#
# class Publishs(List, ObjSave, APIView):
# model = models.Publish
# serializer = PublishSer
#
# def get(self, request):
# return self.get_list(request)
#
# def post(self, request):
# return self.save(request)
#
#
# from django.core.exceptions import ObjectDoesNotExist
#
#
# class Book(APIView):
# def get(self, request, id):
# response = MyResponse()
# try:
# book = models.Book.objects.get(pk=id)
# book_ser = BookSerializer(instance=book, many=False)
# response.book = book_ser.data
# except ObjectDoesNotExist as e:
# response.status = 101
# response.msg = 'id不存在'
#
# except Exception as e:
# print(e)
# response.status = 201
# # response.msg = '您的操作有误'
# response.msg = str(e)
# return Response(response.get_dic)
#
# def put(self, request, id):
# response = MyResponse()
# try:
# book = models.Book.objects.get(pk=id)
# book_ser = BookSerializer(data=request.data, instance=book)
# if not book_ser.is_valid():
# raise Exception('数据校验失败')
# book_ser.save()
# response.book = book_ser.data
# response.msg = '修改成功'
# except ObjectDoesNotExist as e:
# response.status = 101
# response.msg = 'id不存在'
#
# except Exception as e:
# print(e)
# response.status = 201
# # response.msg = '您的操作有误'
# response.msg = str(e)
# return Response(response.get_dic)
#
# def delete(self, request, id):
# response = MyResponse()
# try:
# models.Book.objects.filter(pk=id).delete()
# response.msg = '删除成功'
# except Exception as e:
# print(e)
# response.status = 201
# # response.msg = '您的操作有误'
# response.msg = str(e)
# return Response(response.get_dic)
drf帮咱封装的
# drf帮咱封装的
from rest_framework.mixins import CreateModelMixin, RetrieveModelMixin, ListModelMixin, UpdateModelMixin, \
DestroyModelMixin
from rest_framework.generics import GenericAPIView # class Publishs(GenericAPIView, CreateModelMixin, ListModelMixin):
# queryset = models.Publish.objects
# serializer_class = PublishSer
#
# def get(self, request):
# return self.list(request)
#
# def post(self, request):
# return self.create(request) # DestroyModelMixin:删除
# UpdateModelMixin,:更新
# RetrieveModelMixin :获取一条
# CreateModelMixin:新增一条
# ListModelMixin:获取所有
# class Publish(GenericAPIView, DestroyModelMixin, UpdateModelMixin, RetrieveModelMixin):
# queryset = models.Publish.objects
# serializer_class = PublishSer
# lookup_field='id'
#
# def get(self, request, *args, **kwargs):
# return self.retrieve(request, *args, **kwargs)
#
# def delete(self, request, *args, **kwargs):
# return self.destroy(request, *args, **kwargs)
#
# def put(self, request, *args, **kwargs):
# return self.update(request, *args, **kwargs) # from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, CreateAPIView, ListAPIView, \
# RetrieveAPIView, RetrieveUpdateAPIView, DestroyAPIView
#
# #
# class Publishs(ListCreateAPIView):
# queryset = models.Publish.objects.all()
# serializer_class = PublishSer
#
#
# class Publish(RetrieveUpdateDestroyAPIView):
# queryset = models.Publish.objects.all()
# serializer_class = PublishSer
from rest_framework.parsers import JSONParser
from rest_framework.parsers import FormParser
from rest_framework.viewsets import ModelViewSet
from rest_framework.views import APIView
from rest_framework.renderers import JSONRenderer
class PublishView(ModelViewSet):
# renderer_classes=[JSONRenderer,]
parser_classes=[JSONParser,FormParser]
queryset=models.Publish.objects.all()
serializer_class=PublishSer
ViewSetMixin 重写了as_view方法
from rest_framework.viewsets import ViewSetMixin
# ViewSetMixin 重写了as_view方法 # ViewSetMixin 写在前面,先找ViewSetMixin的as_view方法
# 用了ViewSetMixin ,视图类中,不需要再写get,post,delete....这些函数了,函数名可以自定义
# 而且这个视图类,可以响应多条路由
# class PublishView(ViewSetMixin,APIView):
# def aaa(self,request):
#
# return Response({'status':100})
# def bbb(self,request):
# return Response({'bb': "bbb"}) # 'DEFAULT_PARSER_CLASSES': (
# 'rest_framework.parsers.JSONParser',
# 'rest_framework.parsers.FormParser',
# 'rest_framework.parsers.MultiPartParser'
# )
路由url
from django.conf.urls import url,include
from django.contrib import admin
from app01 import views
# from rest_framework import routers
# router=routers.DefaultRouter()
# # 两个参数,一个是匹配的路由,一个是视图中写的CBV的类
# router.register('publish',views.PublishView)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.Login.as_view()),
# as_view()类的绑定方法
# url(r'^books/', views.Books.as_view()),
# url(r'^publishs/', views.Publishs.as_view()),
# url(r'^publish/(?P<pk>\d+)', views.Publish.as_view()),
# url(r'^book/(?P<id>\d+)', views.Book.as_view()),
# MyViewSet.as_view({'get': 'list', 'post': 'create'})
url(r'^publishs/', views.PublishView.as_view({'get': 'list','post':'create'})),
# url(r'^publish\.(?P<format>\w+)$', views.PublishView.as_view({'get': 'list','post':'create'})),
url(r'^publish/(?P<pk>\d+)', views.PublishView.as_view({'get': 'retrieve','put':'update','delete':'destroy'})), # 原来的视图类,只能响应一个路由
# 现在的视图类,可以响应多个路由
# url(r'^publishs/', views.PublishView.as_view({'get': 'aaa','post':'ddd'})),
#
# url(r'^bbb/', views.PublishView.as_view({'get': 'bbb','post':'ccc'})),
# url(r'', include(router.urls))
]
url控制
解析器
响应器
模板文件查找顺序
-先从项目中找
Django-DRF-图书增删改查 !!!的更多相关文章
- Django ORM 数据库增删改查
Django ORM 数据库增删改查 增 # 创建.增加数据(推荐) models.UserInfo.objects.create(username=') # 创建.增加数据 dic = {'} mo ...
- 基于DRF的图书增删改查练习
功能演示 信息展示 添加功能 编辑功能 删除功能 DRF构建后台数据 本例的Model如下 from django.db import models class Publish(models.Mode ...
- 基于DRF的图书增删改查
功能演示 信息展示 添加功能 编辑功能 删除功能 DRF构建后台数据 本例的Model如下 from django.db import models class Publish(models.Mode ...
- django -- ORM实现图书增删改查
表结构设计 上篇我们实现了出版社的增删改查,出版社数据表有两个字段id和name,那图书的表结构怎么设计呢?图书也要有一个主键id,还要有一个名称title,是哪个出版社的,要有个字段press和Pr ...
- Django数据库操作(增删改查)
Django数据库操作(增删改查) 创建数据库中的一个表 class Business(models.Model): #自动创建ID列 caption = models.CharField(max_l ...
- day 67 django 之ORM 增删改查基础
一 操作基础前提准备 1. 新建django 项目 mysite 子项目app01 ,选择好做路径. 2 .2-1在app01 下面models 中引用 模块 from django.db im ...
- Django models 的增删改查
增 from app01.models import * #create方式一: Author.objects.create(name='Alvin') #create方式二: Author.obje ...
- Django中ORM增删改查
新建模型 class Author(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max ...
- django数据库的增删改查
正常启动服务安装数据库cmd命令:python manage.py makemigrations 创建用户 在pxm里面会有一个py文件..这就是生成了表结构cmd命令:python manage.p ...
- django数据库基本操作-增删改查(tip)-基本
补充:django外键保存 #外键保存 form_data = Form_Data() project, is_created = Project_Name.objects.get_or_create ...
随机推荐
- 04 Django REST Framework 认证、权限和限制
目前,我们的API对谁可以编辑或删除代码段没有任何限制.我们希望有更高级的行为,以确保: 代码片段始终与创建者相关联. 只有通过身份验证的用户可以创建片段. 只有代码片段的创建者可以更新或删除它. 未 ...
- Django生命周期 URL ----> CBV 源码解析-------------- 及rest_framework APIView 源码流程解析
一.一个请求来到Django 的生命周期 FBV 不讨论 CBV: 请求被代理转发到uwsgi: 开始Django的流程: 首先经过中间件process_request (session等) 然后 ...
- Tutorial 01_熟悉常用的Linux操作和Hadoop操作
(一)熟悉常用的Linux 操作cd 命令:切换目录 (1) 切换到目录“/usr/local” (2) 切换到当前目录的上一级目录 (3) 切换到当前登录Linux 系统的用户的自己的主文件夹 ...
- SpringBoot与Mybatis整合的设置
Mybatis和Spring Boot的整合有两种方式: 第一种:使用mybatis官方提供的Spring Boot整合包实现,地址:https://github.com/mybatis/spring ...
- JAVA多线程-内存模型、三大特性、线程池
一.线程的三大特性 原子性.可见性.有序性 1)原子性,即一个操作或者多个操作要么全部执行并且执行的过程不会被任何因素打断,要么就都不执行.原子性其实就是保证数据一致.线程安全一部分. 2)可见性,即 ...
- react学习目录
前面的话 React是如今热门的两大前端框架之一,它设计思路独特,性能卓越,逻辑简单,受到了大量开发者的喜爱.Vue的基本思路是基于HTML模板的扩展,而React的基本思路是基于JS语言的扩展.由于 ...
- docker完整配置nginx+php+mysql
首先了解一个方法: 使用docker exec进入Docker容器 docker在1.3.X版本之后还提供了一个新的命令exec用于进入容器,这种方式相对更简单一些,下面我们来看一下该命令的使用: s ...
- 利用zabbix api添加、删除、禁用主机
python环境配置yum -y install python-pip安装argparse模块pip install -i https://pypi.douban.com/simple/ argpar ...
- RocketMQ_问题_启动控制台console报错,connect to <null> failed
配置如图所示: 问题如图所示: 明明配置了nameserver参数为啥还是connect to null呢? 我的rocketmq部署在CentOS7虚拟机上,原来是没关闭防火墙,执行:systemc ...
- java io系列17之 System.out.println("hello world")原理
我们初学java的第一个程序是"hello world" public class HelloWorld { public static void main(String[] ar ...