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/
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。