Django rest framwork
Restful API
- REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”
- REST从资源的角度类审视整个网络,它将分布在网络中某个节点的资源通过URL进行标识,客户端应用通过URL来获取资源的表征,获得这些表征致使这些应用转变状态
- REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移”
- 所有的数据,不过是通过网络获取的还是操作(增删改查)的数据,都是资源,将一切数据视为资源是REST区别与其他架构风格的最本质属性
- 对于REST这种面向资源的架构风格,有人提出一种全新的结构理念,即:面向资源架构(ROA:Resource Oriented Architecture)
理解RESTful架构 : http://www.ruanyifeng.com/blog/2011/09/restful
RESTful API 设计指南 : http://www.ruanyifeng.com/blog/2014/05/restful_api.html
django中可以使用 Django rest framwork 来实现:http://www.django-rest-framework.org/
一、安装:
pip install djangorestframework pip install markdown pip install django-filter
二、配置
1、注册settings
'rest_framework'
2、配置URL
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
3、引入模块
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)),
以上用的是Django的User表,现在增加一个自定义Test的表
model.py
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)),
现在对表进行增删改查
GET 查: 默认就是GET
POST 增:
PUT 改: 增加url 字段 ,显示每条数据对应的URL
class TestSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Test
fields = ('url','UserName', 'PassWord')
自定义api操作
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)),
这样就可以在页面进行制定的操作,GET,PUT,POST,不能DELETE
http://127.0.0.1:8000/api/servers/?format=json