标签:mamicode 使用 auto 支持 api 基于 HERE app view
restful 协议
1.一切皆是资源
2.book表增删改查
-------- 一切皆是资源操作的只是请求方式
/books/ books
/books/add/ addbook
/book/(\d+)/change/ changebook
/book/(\d+)/delete/ delbook
-------- book表增删改查
/books/ -----get books
/books/add/ -----post addbook
/book/(\d+)/change/ -----put changebook
/book/(\d+)/delete/ -------delete delbook
class Books(View) def get(self,request): pass # 查看所有书籍 def post(self,request): pass # 添加书籍 # 其他请求方法 class Books(View) def get(self,request): pass # 查看具体书籍 def put (self,request,id): pass # 更新某本书籍 def post(self,request,id): pass # 添加书籍 def delete(self,request,id): pass # 删除某本书籍
from django.contrib import admin from django.urls import path,re_path from app01 import views urlpatterns = [ re_path(r‘^admin/‘, admin.site.urls), re_path(‘^/index‘, views.index), re_path(‘^/publishes‘, views.PublishView.as_view()), ]
基于fbv的写法:
from django.shortcuts import render from django.views import View # Create your views here. def index(request): return render(request,"index.html") class PublishView(View): def get(self,request): pass def post(self,request): pass
Django REST framework(DRF)官网:http://www.django-rest-framework.org/
欢迎各位同学在 github 上fork和star该翻译项目,项目有你更精彩。
反序列化方法
class PublishView(View): def get(self, request): # 序列化方式1 # pulish_list = list(models.Publisher.objects.all().values("name","addr")) # return HttpResponse(json.dumps(pulish_list)) # 序列化方式2 # pulish_list=models.Publisher.objects.all() # tem=[] # for obj in pulish_list: # # 循环一个对象的时候可以这样取值 # tem.append({ # "name":obj.name, # "addr":obj.addr, # }) # # return HttpResponse(json.dumps(tem)) # 序列化方式3 # from django.forms.models import model_to_dict # pulish_list = models.Publisher.objects.all() # tem = [] # for obj in pulish_list: # # model_to_dict 可以直接把一个queyset 对象变成字典 # # {‘id‘: 1, ‘name‘: ‘mark的自我修养‘, ‘addr‘: ‘富士康‘}, {‘id‘: 2, ‘name‘: ‘汨汨的自我修养‘, ‘addr‘: ‘湖南‘} # tem.append(model_to_dict(obj)) # # print(tem) # return HttpResponse(json.dumps(tem)) # 序列化方式4: from django.core import serializers pulish_list = models.Publisher.objects.all() ret=serializers.serialize("json",pulish_list) return HttpResponse(ret)
标签:mamicode 使用 auto 支持 api 基于 HERE app view
原文地址:https://www.cnblogs.com/Rivend/p/11787471.html