1. 设置
我们创建django项目tutorial, 和app quickstart:
# 创建新Django项目
django-admin.py startproject tutorial
cd tutorial
# 使用virtualenvwrapper创建Virtualenv
mkvirtualenv env
workon env
# 在env中安装Django 和 Django REST framework
pip install django
pip install djangorestframework
# 创建新app
python manage.py startapp quickstart
然后根据自己的数据库配置设置数据库:
# tutorial/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'database_name',
'USER': 'database_user',
'PASSWORD': 'database_password',
'HOST': '',
'PORT': ''
}
}
...
INSTALLED_APPS = (
...
'quickstart',
'rest_framework',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'PAGINATE_BY': 10
}
最后通过syncdb创建数据库
python manage.py syncdb
2. 序列化
接下来我们创建用于数据序列化的代码:
# quickstart/serializers.py
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')
值得注意的是, 我们使用的是HyperlinkedModelSerializer. 你可以使用主键或者其他关系, 但使用HyperlinkedModelSerializer是一个好的 RESTful 设计.
3. Views
# quickstart/views.py
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from quickstart.serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
允许查看和编辑user 的 API endpoint
"""
queryset = User.objects.all()
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
"""
允许查看和编辑group的 API endpoint
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer
在django_rest_framework中, 所有常见的行为都被归到了ViewSets中. 当然我们可以将这些行为分拆出来, 但使用ViewSets, 使view的逻辑更为清楚.
使用queryset和serializer_class代替model变量, 使我们能更加好的控制API行为, 这也是我们推荐的使用方式.
4. 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.
# Additionally, we include login URLs for the browseable API.
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
)
因为我们使用的是viewset, 所以我们可以使用route class自动生成url conf.
5. 测试
至此我们的设置完成, 可以测试我们的REST API了, 首先启动django服务器:
python ./manage.py runserver
我们可以使用curl命令:
bash: 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"
}
]
}
或者直接使用浏览器也可以: