前言:第一次接触django-rest-framework是在实习的时候。当时也不懂,看到视图用类方法写的感觉很牛逼的样子。因为官网是英文的,这对我的学习还是有一点的阻力的,所以当时也没怎么学。真是太贱了。其实官网有耐心,以我六级410(虽然也没过)的能力,肯定也是能搞懂的阿。追其原因,还是当时自己太浮躁了。
Django rest framework介绍
Django REST framework is a powerful and flexible toolkit for building Web APIs.
Some reasons you might want to use REST framework:
- The Web browsable API is a huge usability win for your developers.
- Authentication policies including packages for OAuth1a and OAuth2.
- Serialization that supports both ORM and non-ORM data sources.
- Customizable all the way down - just use regular function-based views if you don't need the more powerful features.
- Extensive documentation, and great community support.
- Used and trusted by internationally recognised companies including Mozilla, Red Hat, Heroku, and Eventbrite.
中文:
Django REST framework 是用于构建Web API 的强大而灵活的工具包。
我们可能想使用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...
pip install djangorestframework
pip install markdown # Markdown support for the browsable API.
pip install django-filter # Filtering support
...or clone the project from github.
git clone git@github.com:encode/django-rest-framework.git
Add 'rest_framework'
to your INSTALLED_APPS
setting.(记得在setting文件里面添加rest_framework,当然,你还得先安装djangorestframework)
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
文件中。
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:同步数据库
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.
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.
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. 写一些视图,查询数据。
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
...
from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views
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只能由管理员使用
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 文件中有一个关于文章的表:
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)
接下来,只需要写一个序列化器,便可以轻松对数据的进行获取,而且代码看起来特别简洁。
# 在 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__"
这样算刚开始入门了吧,接下来会更深入的学习。