Django REST framework

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  # 删除某本书籍

Django REST framework

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介绍

现在前后端分离的架构设计越来越流行,业界甚至出现了API优先的趋势。
显然API开发已经成为后端程序员的必备技能了,那作为Python程序员特别是把Django作为自己主要的开发框架的程序员,我十分推荐Django REST framework(DRF)这个API框架。
 
Django REST framework(DRF)框架文档齐全,社区较稳定,而且由于它是基于Django这个十分全面的框架而设计开发的,能够让开发者根据自己的业务需要,使用极少的代码量快速的开发一套符合RESTful风格的API,并且还支持自动生成API文档。

Django REST framework(DRF)官网:http://www.django-rest-framework.org/

欢迎各位同学在 github 上forkstar该翻译项目,项目有你更精彩。

Django REST framework

反序列化方法

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)

相关推荐