10.27 rest_framework(1)
2018-10-27 16:48:04
前几天在整理django博客!
新学的rest_framework框架是源于Django的
使用的时候得
pip install djangorestframework
用于前后端分离!
主要看笔记部分!!类似于From组件
越努力越幸运!
永远不要高估自己!
贴上源码,源码都是老师的过程演示,故有些代码冗余!!!所以可以把冗余的代码封装成一个类中
目前还是没有真正用的高restframework !! 最终版本还是restframework, 这是让你明白一下过程!!!!
urls.py
from django.conf.urls import url
from django.contrib import admin from app01 import views
urlpatterns = [ url(r'^admin/', admin.site.urls),
url(r'^publishes/$', views.PublishView.as_view(),name="publish"), # View:view(request)=====APIView:dispatch()
url(r'^publishes/(?P<pk>\d+)/$', views.PublishDetailView.as_view(),name="detailpublish"), # View:view(request)=====APIView:dispatch() url(r'^books/$', views.BookView.as_view(),name="books"),
url(r'^books/(\d+)/$', views.BookDetailView.as_view(),name="detailbook"), ]
app01/view.py
from rest_framework.response import Response
from app01.serilizer import *
from rest_framework.views import APIView class PublishView(APIView):
def get(self,request): # restframework
# 取数据
# print("request.data", request.data)
# print("request.data type", type(request.data))
# print(request._request.GET)
# print(request.GET)
# 序列化
# 方式1:
# publish_list=list(Publish.objects.all().values("name","email")) # 方式2:
# from django.forms.models import model_to_dict
# publish_list=Publish.objects.all()
# temp=[]
# for obj in publish_list:
# temp.append(model_to_dict(obj)) # 方式3:
# django内置的序例化方法
# from django.core import serializers
# ret=serializers.serialize("json",publish_list) # 序列组件
publish_list = Publish.objects.all()
ps = PublishModelSerializers(publish_list, many=True)
return Response(ps.data) def post(self,request):
# 取数据
# 原生request支持的操作
# print("POST",request.POST)
# print("body",request.body)
# # print(request)
# print(type(request))
# from django.core.handlers.wsgi import WSGIRequest
# 新的request支持的操作
# print("request.data",request.data)
# print("request.data type",type(request.data)) #
# post请求的数据
ps = PublishModelSerializers(data=request.data)
if ps.is_valid():
print(ps.validated_data)
ps.save() # create方法
return Response(ps.data)
else:
return Response(ps.errors) class PublishDetailView(APIView):
def get(self, request, pk): publish = Publish.objects.filter(pk=pk).first()
ps = PublishModelSerializers(publish)
return Response(ps.data) def put(self, request, pk):
publish = Publish.objects.filter(pk=pk).first()
ps = PublishModelSerializers(publish, data=request.data)
if ps.is_valid():
ps.save()
return Response(ps.data)
else:
return Response(ps.errors) def delete(self, request, pk):
Publish.objects.filter(pk=pk).delete() return Response() class BookView(APIView):
def get(self,request):
book_list=Book.objects.all()
bs=BookModelSerializers(book_list,many=True,context={'request': request})
return Response(bs.data)
def post(self,request):
# post请求的数据
bs=BookModelSerializers(data=request.data)
if bs.is_valid():
print(bs.validated_data)
bs.save()# create方法
return Response(bs.data)
else:
return Response(bs.errors) class BookDetailView(APIView): def get(self,request,id): book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,context={'request': request})
return Response(bs.data) def put(self,request,id):
book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,data=request.data)
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return Response(bs.errors) def delete(self,request,id):
Book.objects.filter(pk=id).delete() return Response()
app01/serilizer.py
# by luffycity.com from rest_framework import serializers from app01.models import *
# 为queryset,model对象做序列化
class PublishSerializers(serializers.Serializer):
name = serializers.CharField()
email = serializers.CharField() # 类似于ModelForm
# 这个也是做转换的
class PublishModelSerializers(serializers.ModelSerializer):
class Meta:
model=Publish
fields="__all__" # class BookSerializers(serializers.Serializer):
# title = serializers.CharField(max_length=32)
# price = serializers.IntegerField()
# pub_date = serializers.DateField()
# 一对多
# publish=serializers.CharField(source="publish.name")
# 多对多
# #authors=serializers.CharField(source="authors.all")
# authors = serializers.SerializerMethodField()
# 类似于钩子
# def get_authors(self,obj):
# temp=[]
# for obj in obj.authors.all():
# temp.append(obj.name)
# return temp '''
序列化BookSerializers(book_list,many=True)过程:
temp=[]
for obj in book_list:
temp.append({
"title":obj.title,
"price":obj.price,
"pub_date":obj.pub_date,
"publish":str(obj.publish), # obj.publish.name
#"authors":obj.authors.all,
"authors": get_authors(obj)
}) ''' class BookModelSerializers(serializers.ModelSerializer):
class Meta:
model = Book
fields = "__all__" #publish=serializers.CharField(source="publish.pk")
publish=serializers.HyperlinkedIdentityField(
view_name="detailpublish",
lookup_field="publish_id",
lookup_url_kwarg="pk"
) # authors=serializers.CharField(source="authors.all")
# authors = serializers.SerializerMethodField()
# def get_authors(self,obj):
# temp=[]
# for obj in obj.authors.all():
# temp.append(obj.name)
# return temp # def create(self, validated_data):
# print("validated_data",validated_data)
# book=Book.objects.create(title=validated_data["title"],price=validated_data["price"],pub_date=validated_data["pub_date"],publish_id=validated_data["publish"]["pk"])
# book.authors.add(*validated_data["authors"])
#
# return book
models.py
from django.db import models # Create your models here.
from django.db import models # Create your models here. class Book(models.Model):
title=models.CharField(max_length=32)
price=models.IntegerField()
pub_date=models.DateField()
publish=models.ForeignKey("Publish")
authors=models.ManyToManyField("Author")
def __str__(self):
return self.title class Publish(models.Model):
name=models.CharField(max_length=32)
email=models.EmailField()
def __str__(self):
return self.name class Author(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
def __str__(self):
return self.name
笔记!!
day 96 CBV与FBV restful协议 ---- 一切皆是资源,操作只是请求方式 ----book表增删改查
/books/ books
/books/add/ addbook
/books/(\d+)/change/ changebook
/books/(\d+)/delete/ delbook ----book表增删改查
/books/ -----get books ----- 返回当前所有数据
/books/ -----post books ----- 返回提交数据 /books/(\d+)-----get bookdetail ----- 返回当前查看的单条数据
/books/(\d+)-----put bookdetail ----- 返回更新数据
/books/(\d+)-----delete bookdetail ----- 返回空 class Books(View):
def get(self,request):
pass # 查看所有书籍 def post(self,request):
pass # 添加书籍 class BooksDetail(View):
def get(self,request,id):
pass # 查看具体书籍 def put(self,request,id):
pass # 更新某本书籍 def delete(self,request,id):
pass # 删除某本书籍 restframework(Django) ----针对数据:json (1)Django的原生request: 浏览器 ------------- 服务器 "GET url?a=1&b=2 http/1.1\r\user_agent:Google\r\ncontentType:urlencoded\r\n\r\n"
"POST url http/1.1\r\user_agent:Google\r\ncontentType:urlencoded\r\n\r\na=1&b=2" request.body: a=1&b=2
request.POST:
if contentType:urlencoded:
a=1&b=2----->{"a":1,"b":2} (2)restframework 下的APIView: (3)
class PublishSerializers(serializers.Serializer):
name=serializers.CharField()
email=serializers.CharField() obj = PublishSerializers(queryset,many=true)
obj = PublishSerializers(model_obj)
print(obj.data) 总结:
1 reuqest类----源码 2 restframework 下的APIView--源码 url(r'^books/$', views.BookView.as_view(),name="books")# View下的view books/一旦被访问: view(request) ------APIView: dispatch() 3 def dispatch(): 构建request对象
self.request=Request(request)
self.request._request
self.request.GET # get
self.request.data # POST PUT 分发----if get请求:
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(),
self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) # self.get(request, *args, **kwargs) return response 4 序列化类
# from django.core import serializers
# ret=serializers.serialize("json",publish_list) restframework下的序列类 BookModelSerializers
将queryset或者model对象序列成一json数据
bs=BookModelSerializers(book_list,many=True,context={'request': request})
bs=BookModelSerializers(book,context={'request': request}) 还可以做校验数据,json-------》queryset/model-->记录 bs=BookModelSerializers(data=request.data)
if bs.is_valid():
print(bs.validated_data)
bs.save() # 重写create方法
5 操作数据: 以Book表为例
class BookView(APIView):
# 查看所有书籍
def get(self,request):
book_list=Book.objects.all()
bs=BookModelSerializers(book_list,many=True,context={'request': request})
return Response(bs.data) # 添加一本书籍
def post(self,request):
# post请求的数据
bs=BookModelSerializers(data=request.data)
if bs.is_valid():
print(bs.validated_data)
bs.save()# create方法
return Response(bs.data)
else:
return Response(bs.errors) class BookDetailView(APIView):
# 查看一本书籍
def get(self,request,id): book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,context={'request': request})
return Response(bs.data)
# 更新一本书籍
def put(self,request,id):
book=Book.objects.filter(pk=id).first()
bs=BookModelSerializers(book,data=request.data)
if bs.is_valid():
bs.save()
return Response(bs.data)
else:
return Response(bs.errors)
# 删除某一本书籍
def delete(self,request,id):
Book.objects.filter(pk=id).delete() return Response() restframework 1 APIView
2 序列组件
3 视图、
4 组件(认证权限频率)
5 数据解析器
6 分页和Response
10.27 rest_framework(1)的更多相关文章
- 背水一战 Windows 10 (27) - 控件(文本类): TextBlock
[源码下载] 背水一战 Windows 10 (27) - 控件(文本类): TextBlock 作者:webabcd 介绍背水一战 Windows 10 之 控件(文本类) TextBlock 示例 ...
- 第15次Scrum会议(10/27)【欢迎来怼】
一.小组信息 队名:欢迎来怼 小组成员 队长:田继平 成员:李圆圆,葛美义,王伟东,姜珊,邵朔,冉华 小组照片 二.开会信息 时间:2017/10/27 17:20~17:45,总计25min. 地点 ...
- JZOJ 4269. 【NOIP2015模拟10.27】挑竹签
4269. [NOIP2015模拟10.27]挑竹签 (File IO): input:mikado.in output:mikado.out Time Limits: 1000 ms Memory ...
- IP地址最后一位斜杠是什么意思?比如192.168.1.10/27?还有IP地址和子网掩码相加得到的网络地址是什么意思
IP地址最后一位斜杠是什么意思?比如192.168.1.10/27?还有IP地址和子网掩码相加得到的网络地址是什么意思 IP地址最后一位斜杠是什么意思?比如192.168.1.10/27?还有IP地址 ...
- 10.30 rest_framework总结
2018-10-30 20:25:23 终于学完了rest_framework 这个框架! 这个框架有一些基本组件!最重要的就是看源码!要一个类一个类的去找!按顺序! 并且要自己配置类的时候要先看源 ...
- [软件工程基础]2017.10.27 第二次 Scrum 会议
决议 周六前项目交接 Milestone 完成 周六集体开发 游心整理物理网站上的实验流程和绪论复习题 石奇川上线静态版实验流程和绪论复习题库 李煦通构思后端如何实现绪论题库,包括和用户记录的关联方式 ...
- 山东理工大学第七届ACM校赛-飞花的糖果 分类: 比赛 2015-06-26 10:27 15人阅读 评论(0) 收藏
飞花的糖果 Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^ 题目描述 一日,飞花壕大手一挥,买了N个的两两不相同糖果,他想要拿出M个糖果送给他心仪 ...
- Notes of the scrum meeting(2013/10/27)
软工项目组buaa_smile确定自由项目主题及实现功能的scrum meeting meeting time:1:00~2:00p.m.,October 27th,2013 meeting plac ...
- XML操作:2.LINQ TO XML(http://www.cnblogs.com/AlexLiu/archive/2008/10/27/linq.html)
LINQ to XML 建立,读取,增,删,改 LINQ to XML的出现使得我们再也不需要使用XMLDocument这样复杂的一个个的没有层次感的添加和删除.LINQ可以使的生成的XML文档在 ...
随机推荐
- JAVA自学作业01
JAVA自学作业01 1.Hello World 程序 class HelloWorld{ public static void main(String args[]){ System.out.pri ...
- poj3190 Stall Reservations(贪心+STL)
https://vjudge.net/problem/POJ-3190 cin和scanf差这么多么..tle和300ms 思路:先对结构体x升序y升序,再对优先队列重载<,按y升序. 然后依次 ...
- Gradle初识
一.安装配置 gradle官方网站https://gradle.org/,下载下来是一个压缩包,解压到合适的目录即可,然后配置环境变量(GRADLE_HOME,Path),略去. 二.IDEA配置 N ...
- MyBatis(四):mybatis中使用in查询时的注意事项
准备工作 1)创建测试表jobitem CREATE TABLE "jobitem" ( "id" ) NOT NULL AUTO_INCREMENT COMM ...
- cleanmymacchinese下载链接
由于新的chinese版本还没有公开发布下载链接,所以找到如下地址 https://dl.devmate.com/com.macpaw.zh.CleanMyMac3/CleanMyMacChinese ...
- mysql函数之SUBSTRING_INDEX(str,"/",-1)
SUBSTRING_INDEX的用法: •SUBSTRING_INDEX(str,delim,count) 在定界符 delim 以及count 出现前,从字符串str返回自字符串.若count为正值 ...
- edis更新的正确方法
Redis更新的正确方法 https://www.cnblogs.com/westboy/p/8696607.html redis做缓存,怎么更新里面的数据 https://blog.csdn.net ...
- Javascript 解读与思想
Javascript 解读与思想 解读:对底层类库功能的理解 思想:对程序架构的部署思维
- String类源码解析
1. String是使用char[]数组来存储的,并且String值在创建之后就不可以改变了.char[]数组的定义为: /** The value is used for character sto ...
- Guava-Objects使用
前言 Java中的Object提供了很多方法供所有的类使用,特别是toString.hashCode.equals.getClass等方法,在日常开发中作用很大,Guava中包含Objects类,其提 ...