Django Rest Framework(一)
•基于Django
先创建一个django项目,在项目中创建一些表,用来测试rest framework的各种组件
class UserInfo(models.Model):
"""用户信息表"""
user = models.CharField(max_length=32)
pwd = models.CharField(max_length=32) class UserToken(models.Model):
"""用户token表"""
user = models.OneToOneField(to="UserInfo", on_delete=models.CASCADE)
token = models.CharField(max_length=64) class Courses(models.Model):
"""
课程表
"""
name = models.CharField(verbose_name="课程名称", max_length=32)
course_img = models.CharField(verbose_name="课程图片", max_length=64)
level_choices = (
(1, "初级"),
(2, "中级"),
(3, "高级"),
)
level = models.IntegerField(verbose_name="难度", choices=level_choices, default=1) def __str__(self):
return self.name class CourseDetail(models.Model):
"""课程详细表"""
course = models.OneToOneField(to="Courses", on_delete=models.CASCADE)
slogan = models.CharField(verbose_name="口号", max_length=255)
why = models.CharField(verbose_name="为什么要学", max_length=255)
recommend_courses = models.ManyToManyField(verbose_name="推荐课程", to="Courses",
related_name="rc") # related_name设置反向查询的字段,有多个关联时指定某个字段进行反向查询 def __str__(self):
return "课程详细:" + self.course.title class Chapter(models.Model):
"""
课程章节表
"""
num = models.IntegerField(verbose_name="章节")
name = models.CharField(verbose_name="章节名称", max_length=32)
course = models.ForeignKey(verbose_name="所属课程", to="Courses", related_name='coursechapters', on_delete=models.CASCADE) def __str__(self):
return self.name
models.py
from django.contrib import admin
from django.urls import path, include, re_path urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/(?P<version>\w+)/', include("api.urls")),
]
urls.py
from django.urls import re_path
from api.views import courses, account, micro urlpatterns = [
re_path(r'^courses/$', courses.CoursesView.as_view({"get": "list"})),
re_path(r'^courses/(?P<pk>\d+)/', courses.CoursesView.as_view({"get": "retrieve"})), re_path(r'^micro/$', micro.MicroView.as_view({"get": "list"})), re_path(r'^login/$', account.LoginView.as_view()),
]
api/urls.py
•基本流程
请求到来之后,都要执行dispatch方法,dispatch方法根据请求方式不同触发不同的方法,返回不同的内容
url.py
from django.conf.urls import url, include
from api.views import TestView urlpatterns = [
url(r'^test/', TestView.as_view()),
]
views.py
from rest_framework.views import APIView
from rest_framework.response import Response class TestView(APIView):
def dispatch(self, request, *args, **kwargs):
"""
请求到来之后,都要执行dispatch方法,dispatch方法根据请求方式不同触发 get/post/put等方法 注意:dispatch方法有好多好多的功能
"""
return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs):
return Response('GET请求,响应内容') def post(self, request, *args, **kwargs):
return Response('POST请求,响应内容') def put(self, request, *args, **kwargs):
return Response('PUT请求,响应内容')
•路由系统
a.半自动路由
from django.contrib import admin
from django.urls import include, re_path
from api.views import courses urlpatterns = [
re_path(r'^courses/$', courses.CoursesView.as_view({'get': 'list', 'post': 'create'})),
re_path(r'^courses/(?P<pk>\d+)/', courses.CoursesView.as_view(
{'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
]
urls.py
# -*- coding:utf-8 -*-
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from api import models class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__" class UserViewSet(ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = UserSerializer
views.py
b.全自动路由
from django.conf.urls import url, include
from rest_framework import routers
from api.views import users router = routers.DefaultRouter()
router.register(r'users', users.UserViewSet) urlpatterns = [
url(r'^', include(router.urls)),
]
urls.py
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from api import models class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__" class UserViewSet(ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = UserSerializer
views.py
•视图系统
a.ModelViewSet自定义URL
from django.urls import include, re_path
from api.views import courses urlpatterns = [
re_path(r'^courses/$', courses.CoursesView.as_view({'get': 'list', 'post': 'create'})),
re_path(r'^courses/(?P<pk>\d+)/', courses.CoursesView.as_view(
{'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
]
urls.py
# -*- coding:utf-8 -*-
from rest_framework.viewsets import ModelViewSet
from rest_framework import serializers
from api import models class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__" class UserViewSet(ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = UserSerializer
views.py
b.ModelViewSet(rest framework路由)
from django.conf.urls import url, include
from rest_framework import routers
from api.views import users router = routers.DefaultRouter()
router.register(r'users', users.UserViewSet) urlpatterns = [
url(r'^', include(router.urls)),
]
urls.py
from rest_framework import viewsets
from rest_framework import serializers
from api import models class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__" class UserViewSet(viewsets.ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = UserSerializer
views.py
•版本控制
基于url的正则方式传入版本参数进行版本控制:/v1/girls/
settings.py
REST_FRAMEWORK = {
'DEFAULT_VERSION': 'v1', # 默认版本
'ALLOWED_VERSIONS': ['v1', 'v2'], # 允许的版本
'VERSION_PARAM': 'version' # 参数,URL中获取值的key
}
urls.py
from django.urls import path, include, re_path
urlpatterns = [
re_path(r'^api/(?P<version>\w+)/', include("api.urls")),
]
单个视图设置版本
views.py
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning class TestView(APIView):
versioning_class = URLPathVersioning def get(self, request, *args, **kwargs):
# 获取版本
print(request.version)
# 获取版本管理的类
print(request.versioning_scheme) return Response('GET请求,响应内容')
全局设置
settings.py
REST_FRAMEWORK = {
"DEFAULT_VERSIONING_CLASS": 'rest_framework.versioning.URLPathVersioning',
"ALLOWED_VERSIONS": ['v1', 'v2'], # 允许的版本
"VERSION_PARAM": 'version', # 参数
"DEFAULT_VERSION": 'v1', # 默认版本
}
•解析器(parser)
根据请求头content-type选择对应的解析器处理请求体内容
a.只处理请求头content-type为application/json的请求体
views.py
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import JSONParser class TestView(APIView):
parser_classes = [JSONParser, ] def post(self, request, *args, **kwargs):
print(request.content_type) # 获取请求的值,并使用对应的JSONParser进行处理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
print(request.POST)return Response('POST请求,响应内容')
b. 只处理请求头content-type为application/x-www-form-urlencoded 的请求体
views.py
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import FormParser class TestView(APIView):
parser_classes = [FormParser, ] def post(self, request, *args, **kwargs):
print(request.content_type) # 获取请求的值,并使用对应的FormParser进行处理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
print(request.POST) return Response('POST请求,响应内容')
c. 只处理请求头content-type为multipart/form-data的请求体
views.py
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import MultiPartParser class TestView(APIView):
parser_classes = [MultiPartParser, ] def post(self, request, *args, **kwargs):
print(request.content_type) # 获取请求的值,并使用对应的MultiPartParser进行处理
print(request.data) # application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
print(request.POST) return Response('POST请求,响应内容')
d.只处理上传文件
views.py
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import FileUploadParser class TestView(APIView):
parser_classes = [FileUploadParser, ] def post(self, request, filename, *args, **kwargs):
print(filename)
print(request.content_type) # 获取请求的值,并使用对应的FileUploadParser进行处理
print(request.data)
# application/x-www-form-urlencoded 或 multipart/form-data时,request.POST中才有值
print(request.POST)
print(request.FILES)
return Response('POST请求,响应内容')
e.同时使用多个Parser
views
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import JSONParser, FormParser, MultiPartParser class TestView(APIView):
parser_classes = [JSONParser, FormParser, MultiPartParser, ] def post(self, request, filename, *args, **kwargs):
print(request.content_type) # 当同时使用多个parser时,rest framework会根据请求头content-type自动进行比对,并使用对应parser
print(request.data) return Response('POST请求,响应内容')
全局设置:
settings.py
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES':[
'rest_framework.parsers.JSONParser'
'rest_framework.parsers.FormParser'
'rest_framework.parsers.MultiPartParser'
] }
•渲染器
访问url时将数据渲染出不同的格式进行显示
a.浏览器格式API+JSON
单个视图设置
views.py
# -*- coding:utf-8 -*-
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers from rest_framework.renderers import JSONRenderer
from rest_framework.renderers import BrowsableAPIRenderer from api import models class TestSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = "__all__" class CustomBrowsableAPIRenderer(BrowsableAPIRenderer):
def get_default_renderer(self, view):
return JSONRenderer() class TestView(APIView):
renderer_classes = [CustomBrowsableAPIRenderer, ] def get(self, request, *args, **kwargs):
user_list = models.UserInfo.objects.all().first()
ser = TestSerializer(instance=user_list, many=False)
return Response(ser.data)
全局设置
settings.py
REST_FRAMEWORK = {
"DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer",
"rest_framework.renderers.BrowsableAPIRenderer"],
}
Django Rest Framework(一)的更多相关文章
- 使用django rest framework
django 刚接触,想做一些restful api , google了一下,发现有现成的框架.Django REST framework. 对使用做下记录: 安装 从http://django-re ...
- 利用 Django REST framework 编写 RESTful API
利用 Django REST framework 编写 RESTful API Updateat 2015/12/3: 增加 filter 最近在玩 Django,不得不说 rest_framewor ...
- django rest framework 入门
django rest framework 入门1-序列化 Serialization 分类: Python 2013-01-22 22:24 11528人阅读 评论(0) 收藏 举报 djangop ...
- django rest framework
Django-Rest-Framework 教程: 4. 验证和权限 作者: Desmond Chen, 发布日期: 2014-06-01, 修改日期: 2014-06-02 到目前为止, 我们的AP ...
- django rest framework csrf failed csrf token missing or incorrect
django rest framework csrf failed csrf token missing or incorrect REST_FRAMEWORK = { 'DEFAULT_AUTHEN ...
- Django REST Framework学习——Android使用REST方法访问Diango
本文更应该叫做Android如何模拟浏览器访问Django服务器后台. 环境为: Android通过HttpClient访问服务器,从Django中获取json数据,解析显示在UI界面上. 问题为: ...
- 用Django Rest Framework和AngularJS开始你的项目
Reference: http://blog.csdn.net/seele52/article/details/14105445 译序:虽然本文号称是"hello world式的教程&quo ...
- Django REST framework使用ViewSets的自定义路由实现过程
在Django中使用基于类的视图(ClassView),类中所定义的方法名称与Http的请求方法相对应,才能基于路由将请求分发(dispatch)到ClassView中的方法进行处理,而Django ...
- Django REST FrameWork中文教程2:请求和响应
从这一点开始,我们将真正开始覆盖REST框架的核心.我们来介绍几个基本的构建块. 请求对象REST框架引入了Request扩展常规的对象HttpRequest,并提供更灵活的请求解析.Request对 ...
- Django REST framework 中文教程1:序列化
建立环境 在我们做任何事情之前,我们将使用virtualenv创建一个新的虚拟环境.这将确保我们的包配置与我们正在开展的任何其他项目保持良好的隔离. virtualenv envsource env/ ...
随机推荐
- 关于:未能加载文件或程序集“ICSharpCode.SharpZipLib”或它的某一个依赖项异常的解决方案
问题: 今天项目迁移忽然又个ICSharpCode.SharpZipLib.dll 程序包丢失了,于是我在网上下载一个这样的包,结果程序运行就提示:未能加载文件或程序集“ICSharpCode.Sha ...
- ipv6地址抓包分析
拓扑图: 因为多路由,所以采用ospf配置将路由实现互通,从而进行抓包 ospf配置以R1为例 查看R4路由表 做完进行ping通测试 R4pingR3 R4pingR5 进行抓包分析 128报文 1 ...
- ToastCustomUtil【简单的Toast封装类】【自定义Toast的显示风格】
版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 ToastUtil + ToastCustom结合.主要解决低版本机型上系统toast显示不好看的问题. 效果图 代码分析 在Toa ...
- python学习第六讲,python中的数据类型,列表,元祖,字典,之列表使用与介绍
目录 python学习第六讲,python中的数据类型,列表,元祖,字典,之列表使用与介绍. 二丶列表,其它语言称为数组 1.列表的定义,以及语法 2.列表的使用,以及常用方法. 3.列表的常用操作 ...
- cordova+vue打包webapp
使用cordova+vue打包webapp,可以快速给网页套上一个android和ios壳子,完成一个app的开发. 1. 环境准备. (1)node.js 下载地址: https://nodejs ...
- 简述C#中IO的应用
在.NET Framework 中. System.IO 命名空间主要包含基于文件(和基于内存)的输入输出(I/O)服务的相关基础类库.和其他命名空间一样. System.IO 定义了一系列类.接口. ...
- 并发concurrent---1
背景:并发知识是一个程序员段位升级的体现,同样也是进入BAT的必经之路,有必要把并发知识重新梳理一遍. 并发concurrent: 说到并发concurrent,肯定首先想到了线程,创建线程有两种方法 ...
- 关于视频断点续播和H5的本地存储
前段时间,需要在下实现一个视频的断点续播功能,呃,我不会呀,这就很尴尬了.然后呢,在下就想起了一个叫做localStorage的东西.这是个什么东西呢?在网上查阅了一些资料后,在下发现这是webSto ...
- 20190409-层叠の层叠上下文、层叠水平、层叠顺序、z-index、伪元素层叠
写在前面乱七八糟的前言: 此"八卦"的源于,在写下图这个圆滚滚的导航布局时,使用元素及其伪元素加上绝对定位完成,但遇到:before或:after伪元素与元素的层叠顺序,就是伪元素 ...
- SQLserver数据库反编译生成Hibernate实体类和映射文件
一.建立项目和sqlserver数据库 eclipse,我使用的版本是neon3 二.Data Source Explorer 选择OK 在data source Explorer的Database ...