理解RESTful架構 : http://www.ruanyifeng.com/blog/2011/09/restful html
RESTful API 設計指南 : http://www.ruanyifeng.com/blog/2014/05/restful_api.html python
django中可使用 Django rest framwork 來實現:http://www.django-rest-framework.org/web
1、安裝:django
pip install djangorestframework pip install markdown pip install django-filter
'rest_framework'
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
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') class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ url(r'^', include(router.urls)),
class Test(models.Model): UserName = models.CharField(max_length=50) PassWord = models.CharField(max_length=50)
from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from web_api import models class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class TestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Test fields = ('UserName', 'PassWord') class TestViewSet(viewsets.ModelViewSet): queryset = models.Test.objects.all() serializer_class = TestSerializer router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'tests', TestViewSet) urlpatterns = [ url(r'^', include(router.urls)),
class TestSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Test
fields = ('url','UserName', 'PassWord')
from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET','PUT','POST']) #定義只能容許接收的請求,屏蔽DELETE def servers(request): method = request.method if method == 'POST': pass elif method == 'PUT': pass return Response('ok') #用rest提供的Response,返回更友好的界面
urlpatterns = [ url(r'servers/',views.servers), url(r'^', include(router.urls)),