标签:2.7 max eric import sel -o install 可选依赖 1.9
Django REST framework 是一个强大且灵活的工具包,用以构建Web APIs。
- 在线可视的API,对于赢得你的开发者们十分有用
- 验证策略涵盖了OAuth1a和OAuth2
- 同时支持ORM和非ORM数据源的序列化
- 可以配置各个环节,若无需更多强大的特性,使用一般基于类(function-based)的视图(views)即可
- 大量的文档,强力的社区支持
- 大公司如同Mozilla和Eventbrite,也是忠实的使用者
REST framework 有以下的要求:
下面是可选的包:
pip install djangorestframework pip install markdown # 可选依赖包 pip install django-filter # 可选依赖包
INSTALLED_APPS = ( ... ‘rest_framework‘, ) REST_FRAMEWORK = { # 编码格式 ‘UNICODE_JSON‘: False, }
from django.db import models class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() def __str__(self): return self.name
from django.conf.urls import url from django.contrib import admin from rest_demoimport views urlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^authors/$‘, views.AuthorsView.as_view()), url(r‘^authors/(\d+)/$‘, views.AuthorsDetailView.as_view()), ]
from rest_framework import serializers from rest_demo import models class AuthorModelSerializers(serializers.ModelSerializer): class Meta: model = models.Author fields = ‘__all__‘
from rest_demo import serializer from rest_framework.views import APIView from rest_framework.response import Response from rest_demo import models class AuthorsView(APIView): def get(self,request): ‘‘‘ 查询所有作者 :param request: :return: ‘‘‘ author_list = models.Author.objects.all() auts = serializer.AuthorModelSerializers(author_list,many=True) return Response(auts.data) def post(self,request): ‘‘‘ 添加作者 :param request: :return: ‘‘‘ auts = serializer.AuthorModelSerializers(data=request.data) if auts.is_valid(): auts.save() return Response(auts.data) return Response(auts.errors) class AuthorsDetailView(APIView): def get(self,request,id): ‘‘‘ 查询单条作者 :param request: :param id: :return: ‘‘‘ author = models.Author.objects.filter(pk=id).first() auts = serializer.AuthorModelSerializers(author) return Response(auts.data) def put(self,request,id): ‘‘‘ 修改单条作者 :param request: :param id: :return: ‘‘‘ author = models.Author.objects.filter(pk=id).first() auts = serializer.AuthorModelSerializers(instance=author,data=request.data) if auts.is_valid(): auts.save() return Response(auts.data) return Response(auts.errors) def delete(self,request,id): ‘‘‘ 删除单条作者 :param request: :param id: :return: ‘‘‘ models.Author.objects.filter(pk=id).delete() return Response()
标签:2.7 max eric import sel -o install 可选依赖 1.9
原文地址:https://www.cnblogs.com/fu-yong/p/9052504.html