Django REST framework快速入门指南

项目设置python

建立一个名为tutorial的新Django项目,而后开始一个名为quickstart的新应用程序。数据库

 1 # Create the project directory
 2 mkdir tutorial
 3 cd tutorial
 4 
 5 # Create a virtualenv to isolate our package dependencies locally
 6 virtualenv env
 7 source env/bin/activate  # On Windows use `env\Scripts\activate`
 8 
 9 # Install Django and Django REST framework into the virtualenv
10 pip install django
11 pip install djangorestframework
12 
13 # Set up a new project with a single application
14 django-admin.py startproject tutorial .  # Note the trailing '.' character
15 cd tutorial
16 django-admin.py startapp quickstart
17 cd ..
View Code

项目布局应该以下所示:django

$ pwd
<some path>/tutorial
$ find .
.
./manage.py
./tutorial
./tutorial/__init__.py
./tutorial/quickstart
./tutorial/quickstart/__init__.py
./tutorial/quickstart/admin.py
./tutorial/quickstart/apps.py
./tutorial/quickstart/migrations
./tutorial/quickstart/migrations/__init__.py
./tutorial/quickstart/models.py
./tutorial/quickstart/tests.py
./tutorial/quickstart/views.py
./tutorial/settings.py
./tutorial/urls.py
./tutorial/wsgi.py
View Code

在项目目录中建立应用程序可能看起来很不寻常。使用项目的名称空间避免了与外部模块的名称冲突(主题不在快速入门的范围内)。json

如今第一次同步您的数据库:api

python manage.py migrate

咱们还将建立一个名为admin的初始用户,其密码为password123。稍后在咱们的示例中,咱们将以用户身份进行身份验证浏览器

python manage.py createsuperuser --email admin@example.com --username admin

一旦你创建了一个数据库并建立了初始用户并准备就绪,打开应用程序的目录,咱们就会获得编码......bash

Serializers

首先咱们要定义一些序列化器。咱们来建立一个名为tutorial / quickstart / serializers.py的新模块,咱们将用它来表示数据。服务器

 1 from django.contrib.auth.models import User, Group
 2 from rest_framework import serializers
 3 
 4 
 5 class UserSerializer(serializers.HyperlinkedModelSerializer):
 6     class Meta:
 7         model = User
 8         fields = ('url', 'username', 'email', 'groups')
 9 
10 
11 class GroupSerializer(serializers.HyperlinkedModelSerializer):
12     class Meta:
13         model = Group
14         fields = ('url', 'name')
View Code

请注意,在这种状况下,咱们使用超连接关系,使用HyperlinkedModelSerializer。您还可使用主键和各类其余关系,但超连接是良好的RESTful设计。app

Views

对,咱们最好写一些意见。打开tutorial / quickstart / views.py并输入框架

 1 from django.contrib.auth.models import User, Group
 2 from rest_framework import viewsets
 3 from tutorial.quickstart.serializers import UserSerializer, GroupSerializer
 4 
 5 
 6 class UserViewSet(viewsets.ModelViewSet):
 7     """
 8     API endpoint that allows users to be viewed or edited.
 9     """
10     queryset = User.objects.all().order_by('-date_joined')
11     serializer_class = UserSerializer
12 
13 
14 class GroupViewSet(viewsets.ModelViewSet):
15     """
16     API endpoint that allows groups to be viewed or edited.
17     """
18     queryset = Group.objects.all()
19     serializer_class = GroupSerializer
View Code

咱们不是编写多个视图,而是将全部常见行为归为一类,称为ViewSets。

若是须要,咱们能够轻松地将这些视图分解为单个视图,但使用视图集可使视图逻辑组织得很是好,而且很是简洁。

URLs

好的,如今让咱们连线API网址。在tutorial / urls.py上...

 1 from django.conf.urls import url, include
 2 from rest_framework import routers
 3 from tutorial.quickstart import views
 4 
 5 router = routers.DefaultRouter()
 6 router.register(r'users', views.UserViewSet)
 7 router.register(r'groups', views.GroupViewSet)
 8 
 9 # Wire up our API using automatic URL routing.
10 # Additionally, we include login URLs for the browsable API.
11 urlpatterns = [
12     url(r'^', include(router.urls)),
13     url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
14 ]
View Code

由于咱们使用视图集而不是视图,因此咱们能够自动为咱们的API生成URL conf,只需向路由器类注册视图集。

一样,若是咱们须要更多地控制API URL,咱们能够简单地使用常规的基于类的视图,并明确写入URL conf。

最后,咱们将包括默认的登陆和注销视图,以用于可浏览的API。这是可选的,但若是您的API须要身份验证而且您想使用可浏览的API,则会颇有用。

Settings

将'rest_framework'添加到INSTALLED_APPS。设置模块将位于tutorial / settings.py中

1 INSTALLED_APPS = (
2     ...
3     'rest_framework',
4 )
View Code

好的,咱们完成了。

Testing our API

咱们如今准备测试咱们构建的API。让咱们从命令行启动服务器。

python manage.py runserver

咱们如今可使用curl等工具从命令行访问咱们的API

bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://127.0.0.1:8000/users/1/",
            "username": "admin"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}
View Code

或者使用httpie命令行工具

bash: http -a admin:password123 http://127.0.0.1:8000/users/

HTTP/1.1 200 OK
...
{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "email": "admin@example.com",
            "groups": [],
            "url": "http://localhost:8000/users/1/",
            "username": "paul"
        },
        {
            "email": "tom@example.com",
            "groups": [                ],
            "url": "http://127.0.0.1:8000/users/2/",
            "username": "tom"
        }
    ]
}
View Code

或者直接经过浏览器,转到URL http://127.0.0.1:8000/users/

若是您经过浏览器工做,请确保使用右上角的控件进行登陆。

若是您想更深刻地了解REST框架如何配合使用the tutorial 或者开始浏览 API guide.

相关文章
相关标签/搜索