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.

相關文章
相關標籤/搜索