Django REST framework
如果要在django项目实现restful api, 那么一个方便的做法就是使用django rest framework这个app。
http://www.django-rest-framework.org/
1.安装##
pip install djangorestframework
就像安装普通应用一样
然后修改项目的settings.py
INSTALLED_APPS = {
...
'rest_framework',
}
如果你还要使用rest_framework的browserable API(这个可以在浏览器中查看), 那么你可能也要添加登录views.在urls.py中添加
urlpatterns = {
...
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framwork')),
2.示例##
首先建立一个项目和应用:
django-admin startproject rest
cd rest
django-admin startapp post
python manage.py migrate
然后跟着1里面的步骤安装rest_framework
接着我们在post/models.py里面建立我们的Post对象:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=40)
content = models.TextField()
settings.py:
INSTALLED_APPS = [
...
'post.apps.PostConfig',
]
为了方便我们创建一个admin用户并且添加post对象:
python manage.py createsuperuser
post/models.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
将post对象迁移到数据库
python manage.py makemigrations post
python manage.py migrate
然后通过在admin视图里面建立几个post对象。
下面我们要建立post对象的链接,这个是rest_framework需要用来控制post对象。
新建post/serializers.py
from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Post
fields = ('title', 'content', 'pub_date')
然后要显示这些需要写viewset, 就相当于集成了rest操作的视图集。
from django.shortcuts import render
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
然后使用rest_framework的router, 就不用我们自己配置urls了
建立post/urls.py
from django.conf.urls import url, include
from rest_framework import routers
from .views import PostViewSet
router = routers.DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
urlpatterns = [
url(r'^post/', include('post.urls'))
]
到这里就可以了。
python manage.py runserver
然后打开浏览器: localhost:8000/post/posts
就可以看到Django REST framework的视图,并且显示了你的Post对象,而且提供了GET, POST等RESTful操作。