Django REST framework 是用于构建Web API 的强大而灵活的工具包。本质上DRF是django的一个app(startproject)
DRF中文文档:http://www.sinodocs.cn/
安装:安装在想用的Python解释器下,例如:在终端cd到/python/lib/site-packages,然后执行 pip install djangorestframework
DRF的一些组件:
1 APIView (所有的功能都是基于APIView的)*****
2 解析器组件 *****
3 序列化组件 *****
4 视图组件
5 认证组件 *****
6 权限组件 *****
7 频率组件
8 url注册器组件
9 响应器组件
10 分页器组件
11 filter:过滤、查找、排序
1.APIView
2.解析器组件
3.序列化组件(serializers)的使用及接口设计
4.视图组件(mixin,genericview,viewset)
视图组件是用来优化接口逻辑的
(1) 使用视图组件的mixin进行接口逻辑优化
(2) 使用视图组件的view进行接口逻辑优化
(3) 使用视图组件的viewset进行接口逻辑优化
5.认证组件(token)
6.权限组件
7.频率组件
8.url注册器组件
9.响应器组件
10.分页器组件
11.filter
字段过滤
一般过滤可以重写get_queryset方法实现,这时候就可以去掉queryset这个属性了:
现在就可以通过在url里指定参数price_min来实现对获取到的商品价格的过滤了。
注意在使用这种方法时,要在router.register里配置base_name,不然运行不了。
还可以使用django-filter,这个要把它注册为app,然后就能用了(因为这时候不需要重写get_queryset方法了,所以就需要把queryset这个属性拿回来)。然后可以自定义一个filters.py用来写自定义过滤规则的过滤器:
然后在views.py的相关视图类里指定filter_class为这个自定义的过滤器类:
在这个例子里配置完了之后,效果就是可以在url里指定min_price和max_price的值,来控制所返回的JSON中上shop_price值所在的区间,实现区间过滤;使用name实现模糊查询。
查找
要实现查找,只要在视图层配置filters.SearchFilter和search_fields=要查找的字段元组即可:
一些符号可以实现复杂的查找方式,比如以。。开头,全文搜索之类的。
排序
要实现排序,只要在视图层配置filters.OrderingFilter和ordering_fields=要排序的字段即可:
使用REST框架的一些原因:
- Web浏览API对于开发人员来说是一个巨大的可用性。
- 认证策略包括OAuth1a和OAuth2的包。
- 支持ORM和非ORM数据源的序列化。
- 如果你不需要更强大的功能,就可以使用常规的基于功能的视图。
- 广泛的文档和良好的社区支持。
- 包括Mozilla、Red Hat、Heroku和Eventbrite在内的国际知名公司使用和信任。
Funding
REST framework is a collaboratively(合作地) funded project(基金项目). If you use REST framework commercially we strongly encourage you to invest(投资) in its continued development(可持续发展) by signing up for a paid plan.(注册付费计划)
Every single sign-up helps us make REST framework long-term financially sustainable(财务上可持续发展)
Many thanks to all our wonderful sponsors(赞助商), and in particular to our premium backers(优质的支持者), Rover, Sentry, Stream, Machinalis, and Rollbar.
Requirements
REST framework requires the following:
- Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6)
- Django (1.10, 1.11, 2.0 alpha)
The following packages are optional:
- coreapi (1.32.0+) - Schema generation support.
- Markdown (2.1.0+) - Markdown support for the browsable API.
- django-filter (1.0.1+) - Filtering support.
- django-crispy-forms - Improved HTML display for filtering.
- django-guardian (1.1.1+) - Object level permissions support.
以下软件包是可选的:
- coreapi(1.32.0+) - 支持模式生成。
- Markdown(2.1.0+) - 可浏览API的Markdown支持。
- django-filter(1.0.1+) - 过滤支持。
- django-crispy-forms - 改进的HTML显示过滤。
- django-guardian(1.1.1+) - 对象级权限支持。
Installation
Install using pip
, including any optional packages you want...
1
2
3
|
pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django - filter # Filtering support |
...or clone the project from github.
1
|
git clone git@github.com:encode / django - rest - framework.git |
Add 'rest_framework'
to your INSTALLED_APPS
setting.(记得在setting文件里面添加rest_framework,当然,你还得先安装djangorestframework)
1
2
3
4
|
INSTALLED_APPS = ( ... 'rest_framework' , ) |
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py
file.
如果您打算使用可浏览的API,您可能还需要添加REST框架的登录和注销视图。将以下内容添加到您的根urls.py
文件中。
1
2
3
4
|
urlpatterns = [ ... url(r '^api-auth/' , include( 'rest_framework.urls' , namespace = 'rest_framework' )) ] |
Note that the URL path can be whatever you want, but you must include 'rest_framework.urls'
with the 'rest_framework'
namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.
请注意,URL路径可以是任何你想要的,但你必须包括'rest_framework.urls'
与'rest_framework'
命名空间。您可以在Django 1.9+中省略命名空间,REST框架将为您设置。
Quickstart
Can't wait to get started? The quickstart guide is the fastest way to get up and running, and building APIs with REST framework.
说了一堆,直接来个demo,快速上手,看看效果。官网请看:http://www.django-rest-framework.org/tutorial/quickstart/
首先肯定得先创建django程序啦,接着创建APP,这里我创建了一个quickstart的app。
Now sync your database for the first time:同步数据库
1
|
python manage.py migrate |
创建超级用户用于登陆。We'll also create an initial user named admin
with a password of password123
. We'll authenticate as that user later in our example.
1
|
python manage.py createsuperuser |
Serializers
首先我们要定义一些序列化程序。在quickstart这个APP下创建serializers文件,用于展示数据。
First up we're going to define some serializers. Let's create a new module named tutorial/quickstart/serializers.py
that we'll use for our data representations.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ( 'url' , 'username' , 'email' , 'groups' ) class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ( 'url' , 'name' ) |
Notice that we're using hyperlinked relations in this case, with HyperlinkedModelSerializer
. You can also use primary key and various other relationships, but hyperlinking is good RESTful design.
请注意,在这种情况下,我们正在使用超链接关系HyperlinkedModelSerializer
。您还可以使用主键和各种其他关系,但超链接是好的RESTful设计。
Views
Right, we'd better write some views then. Open tutorial/quickstart/views.py
and get typing. 写一些视图,查询数据。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
from django.contrib.auth.models import User, Group from rest_framework import viewsets from tutorial.quickstart.serializers import UserSerializer, GroupSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects. all ().order_by( '-date_joined' ) serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects. all () serializer_class = GroupSerializer |
Rather than write multiple views we're grouping together all the common behavior into classes called ViewSets
.
We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise.
我们不是编写多个视图,而是将所有常见的行为组合到一个名为viewset的类中。
如果需要的话,我们可以很容易地将它们分解为单独的视图,但是使用viewset使视图逻辑组织得很好,并且非常简洁。
URLs
Okay, now let's wire up the API URLs. On to tutorial/urls.py
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from django.conf.urls import url, include from rest_framework import routers from tutorial.quickstart import views <br> router = routers.DefaultRouter() router.register(r 'users' , views.UserViewSet) router.register(r 'groups' , views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r '^' , include(router.urls)), url(r '^api-auth/' , include( 'rest_framework.urls' , namespace = 'rest_framework' )) ] |
Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class.
我们可以通过简单地使用路由器类注册该视图来自动生成API的URL conf。
Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly.
再次,如果我们需要对API URL的更多控制,我们可以简单地将其下拉到使用常规的基于类的视图,并明确地编写URL conf。
Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API.
最后,我们将包括默认登录和注销视图,以便与可浏览的API一起使用。这是可选的,但如果您的API需要身份验证,并且您想要使用可浏览的API,那么这是非常有用的。
Settings
We'd also like to set a few global settings. We'd like to turn on pagination, and we want our API to only be accessible to admin users. The settings module will be in tutorial/settings.py
我们也想设置一些全局设置。我们想打开分页,我们希望我们的API只能由管理员使用
1
2
3
4
5
6
7
8
9
10
11
|
INSTALLED_APPS = ( ... 'rest_framework' , ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES' : [ 'rest_framework.permissions.IsAdminUser' , ], 'PAGE_SIZE' : 10 } |
Okay, we're done.
效果图:
主界面,好像啥也没有……
用超级用户登陆后的界面。
有增删改查的功能。
快速了解REST framework组件
接下来了解下rest framework 的所有组件,并且得知它们是如何组合在一起的,这是非常值得去学习的。
- 1 - Serialization 序列化
- 2 - Requests & Responses 请求 & 响应
- 3 - Class-based views 基于类的视图
- 4 - Authentication & permissions 身份验证 & 权限
- 5 - Relationships & hyperlinked APIs
- 6 - Viewsets & routers 视图和路由
- 7 - Schemas & client libraries 模式和客户端库
Serialization 序列化
这里不对普通的序列化作介绍。接下来使用 ModelSerializers model序列化让代码更少,更简洁。Django提供了form和modelform一样,REST框架包括了序列化器类和模型序列化器类。
例如 models 文件中有一个关于文章的表:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
class Article(models.Model): """文章资讯""" title = models.CharField(max_length = 255 , unique = True , db_index = True , verbose_name = "标题" ) source = models.ForeignKey( "ArticleSource" , verbose_name = "来源" ) article_type_choices = (( 0 , '资讯' ), ( 1 , '视频' )) article_type = models.SmallIntegerField(choices = article_type_choices, default = 0 ) brief = models.TextField(max_length = 512 , verbose_name = "摘要" ) head_img = models.CharField(max_length = 255 ) content = models.TextField(verbose_name = "文章正文" ) pub_date = models.DateTimeField(verbose_name = "上架日期" ) offline_date = models.DateTimeField(verbose_name = "下架日期" ) status_choices = (( 0 , '在线' ), ( 1 , '下线' )) status = models.SmallIntegerField(choices = status_choices, default = 0 , verbose_name = "状态" ) order = models.SmallIntegerField(default = 0 , verbose_name = "权重" , help_text = "文章想置顶,可以把数字调大" ) comment_num = models.SmallIntegerField(default = 0 , verbose_name = "评论数" ) agree_num = models.SmallIntegerField(default = 0 , verbose_name = "点赞数" ) view_num = models.SmallIntegerField(default = 0 , verbose_name = "观看数" ) collect_num = models.SmallIntegerField(default = 0 , verbose_name = "收藏数" ) tags = models.ManyToManyField( "Tags" , blank = True , verbose_name = "标签" ) date = models.DateTimeField(auto_now_add = True , verbose_name = "创建日期" ) def __str__( self ): return "%s-%s" % ( self .source, self .title) |
接下来,只需要写一个序列化器,便可以轻松对数据的进行获取,而且代码看起来特别简洁。
1
2
3
4
5
6
7
8
9
10
11
12
|
# 在 serilallzer.py 文件可以这样写 # 如果想使用哪个model进行序列化,照此类推即可 # fields 如果想要获取所有字段, 使用"__all__" # fields 如果只是想要获取一部分数据呢, 那么在 fields 中加入所序列化的model的字段即可 from rest_framework.serializers import ModelSerializer class ArticleSerializer(ModelSerializer): class Meta: model = models.Article fields = ( "id" , "title" , "article_type" , "content" , ) or "__all__" |