首页 > Python > Django REST framework 编写 RESTful API(一)
2016
11-09

Django REST framework 编写 RESTful API(一)

 

关于RESTful介绍可以参看文章http://www.ttfde.top/archives/336.html 

Django REST framework的官网:http://www.django-rest-framework.org/

一、先看一下官网的例子

1:使用pip安装

pip install djangorestframework
pip install markdown       
# Markdown support for the browsable API.
pip install django-filter  
# Filtering support

2.安装APP

INSTALLED_APPS = (
    ...
    'rest_framework',)

3.在根urls下创建Serializer、ViewSet、router

当然也可以再创建的其他app下创建,这里只是一个简单演示

from django.conf.urls import url, include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
# 序列化
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff')
# 视图设置ViewSet
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
# 自动路由设置
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    url(r'^', include(router.urls)),
]

在浏览器输入http://127.0.0.1:8000/, 就能看到'users' API. 

 

二、一个完整的实例

1:使用pip安装

pip install djangorestframework
pip install markdown       
# Markdown support for the browsable API.
pip install django-filter  
# Filtering support

2:建立django工程,创建app

django admin startproject restful
django admin startapp demo

3:配置restful环境

#安装rest_framework APP:修改restful/settings.py
#在INSTALLED_APPS 添加 'rest_framework'
INSTALLED_APPS = (
    ...

    'rest_framework',
)

4:编写model层 /demo/model.py

from django.db import models
# Create your models here.
class User(models.Model):
        username = models.CharField(max_length=20,blank=True)
        password = models.CharField(max_length=20,blank=True)
        def __str__(self):
            return self.username

 5:配置数据库,配置后台管理 /demo/admin.py

python manage.py makemigratons
python manage.py migrate
python manage.py createsuperuser

from django.contrib import admin
#Register your models here.
from demo.models import User
admin.site.register(User)

此时登陆后台添加一些数据

6:编写序列化模块 /demo/serializer.py

# coding=utf-8
from rest_framework import serializers
from demo.models import User
class UserSerializer(serializers.ModelSerializer):
   class Meta:
       model = User
       fields = ("id","username","password")

 7:配置url

#根url restful/url.py
urlpatterns = [
        url(r'^admin/', include(admin.site.urls)),
        url(r'^api/demo/',include('demo.urls')),
    ]
#APP URL demo/urls.py
urlpatterns = [
        url(r'^user/$',views.User_list),
        url(r'^user/(?P<pk>[0-9]+)/$',views.User_detial),
    ]

8:编写views层 demo/views.py

    import json
    from django.shortcuts import render
    # Create your views here.
    from rest_framework import status
    from rest_framework.decorators import api_view
    from rest_framework.response import Response
    from demo.models import User
    from demo.serializer import UserSerializer

    @api_view(['GET','POST'])
    def User_list(request):
        if request.method=="GET":
            users = User.objects.all()
            serializer = UserSerializer(users,many=True)
            return Response(serializer.data)
        elif request.method == 'POST':
            print request.body
            serializer = UserSerializer(data=json.loads(request.body))
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @api_view(['GET', 'PUT', 'DELETE']) #
    def User_detial(request,pk):
        try:
            user = User.objects.get(pk=pk)
        except User.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)
        if request.method == "GET":
            serializer = UserSerializer(user)
            return Response(serializer.data)
        elif request.method == "PUT":
            serializer = UserSerializer(user,data=json.loads(request.body))
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)
            else:
                return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
        elif request.method == "DELETE":
            user.delete()
            return Response(status=status.HTTP_204_NO_CONTENT)

9:测试

①获取用户列表
浏览器访问http://127.0.0.1:8000/api/demo/user/
②通过postman来测试,返回的是json数据。可进行GET,POST,PUT,DELETE.

作者:admin
admin
TTF的家园-www.ttfde.top 个人博客以便写写东西,欢迎喜欢互联网的朋友一起交流!

本文》有 0 条评论

留下一个回复