0,快速教程

Quickstart

We're going to create a simple API to allow admin users to view and edit the users and groups in the system.python

咱們將創建一個簡單的API例子,只有超級用戶admin才能查看和編輯系統的用戶和用戶組信息。sql

Project setup

Create a new Django project named tutorial, then start a new app called quickstart.數據庫

創建一個名爲tutorial的新的Django工程,而後在該工程中建立一個名爲 quickstat 的新app。django

# Set up a new project
django-admin.py startproject tutorial
cd tutorial

# Create a virtualenv to isolate our package dependencies locally
virtualenv env
source env/bin/activate  # On Windows use `env\Scripts\activate`# Install Django and Django REST framework into the virtualenv
pip install django
pip install djangorestframework

# Create a new app
python manage.py startapp quickstart
 

Next you'll need to get a database set up and synced. If you just want to use SQLite for now, then you'll want to edit your tutorial/settings.py module to include something like this:json

接下來須要設置並同步數據庫。若是僅僅使用SQLite,須要像下面那樣去編輯文件 tutorial/settings.py:api

DATABASES ={'default':{'ENGINE':'django.db.backends.sqlite3','NAME':'database.sql','USER':'','PASSWORD':'','HOST':'','PORT':''}}

The run syncdb like so:瀏覽器

同步數據庫:app

python manage.py syncdb

Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding...框架

一旦設置同步好數據庫,咱們就能夠在app的目錄下面編碼了。curl

Serializers

序列化器

First up we're going to define some serializers in quickstart/serializers.py that we'll use for our data representations.

首先定義一些序列化器用來呈現咱們的數據,編輯文件 quickstart/serializer.py以下:

from django.contrib.auth.models importUser,Groupfrom rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
  classMeta: model
=User fields =('url','username','email','groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
  classMeta: 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 quickstart/views.py and get typing.

在 quickstart/views.py 中編寫視圖函數。

from django.contrib.auth.models importUser,Groupfrom rest_framework import viewsets
from quickstart.serializers importUserSerializer,GroupSerializer

class UserViewSet(viewsets.ModelViewSet):

  """ API endpoint that allows users to be viewed or edited. """ queryset =User.objects.all() 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.

比起寫多個視圖函數,咱們寧願寫一個,把全部的行爲寫到一個 ViewSets 的類中,這樣更加有組織,更加簡明。

Notice that our viewset classes here are a little different from those in the frontpage example, as they include queryset and serializer_class attributes, instead of a model attribute.

注意,這裏的 ViewSet 類跟以前的 frontpage example 有點不同,這裏的ViewSet 類中包含 queryset 和 serializer_class 屬性,在frontpage example 中是一個model屬性。

For trivial cases you can simply set a model attribute on the ViewSet class and the serializer and queryset will be automatically generated for you. Setting the queryset and/or serializer_class attributes gives you more explicit control of the API behaviour, and is the recommended style for most applications.

在一些簡單的 ViewSet 類中,你能夠簡單地設置一個model屬性, queryset 和 serializer_class 屬性會自動地產生。設置queryset 和(或者) serializer_class 屬性能夠顯示地控制API的行爲,這也是大多數應用所推崇的方式。

URLs

URL 配置

Okay, now let's wire up the API URLs. On to tutorial/urls.py...

如今配置 API 的URLs,在 tutorial/urls.py 中添加以下代碼:

from django.conf.urls import patterns, url, include
from rest_framework import routers
from 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.使用自動 URL 調度
# Additionally, we include login URLs for the browseable API. 另外,爲可瀏覽 API 包含登陸 URLs
urlpatterns
= patterns('', 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.

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.

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.

因爲咱們使用 ViewSet 類 而不是視圖函數, 經過一個 router 類註冊 ViewSet 類就能夠爲 API 自動產生 URL 的配置。

若是咱們須要更多地控制  API URL,咱們能夠放棄這種方式,而是顯示地編寫 URL 配置。

最後,咱們爲可瀏覽的 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的訪問權限,此處只有超級用戶 admin 可使用API。在 tutorial/settings.py 設置以下:

INSTALLED_APPS =(...'rest_framework',)

REST_FRAMEWORK ={'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAdminUser',),'PAGINATE_BY':10}

好了,作完了。


Testing our API

測試 API

We're now ready to test the API we've built. Let's fire up the server from the command line.

在工程的根目錄中開啓服務:

python ./manage.py runserver

We can now access our API, both from the command-line, using tools like curl...

使用 curl 工具訪問 API:

curl -H 'Accept: application/json; indent=4'-u admin:password 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"} ] }

 

Or directly through the browser...

或者直接在瀏覽器中查看:

http://127.0.0.1:8000/users/

Quick start image

If you want to get a more in depth understanding of how REST framework fits together head on over to the tutorial, or start browsing the API guide.

若是你想進一步理解 REST 框架,訪問the tutorial 或者 API guide

相關文章
相關標籤/搜索