版本控制、序列化

版本控制有利于我们根据客户端的版本不同做出不同的处理,比如微信的版本不同

url.py

from django.conf.urls import url, include
from web.views import TestView

urlpatterns = [
    url(r'^(?P<version>[v1|v2]+)/test/', TestView.as_view(), name='test'),#允许版本v1和版本v2共存
]

settings.py

 
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.URLPathVersioning'#导入路径
'DEFAULT_VERSION': 'v1', # 默认版本 

'ALLOWED_VERSIONS': ['v1', 'v2'], # 允许的版本 '

VERSION_PARAM': 'version' # URL中获取值的key
}
 

views

from rest_framework.versioning import QueryParameterVersioning,URLPathVersioning

class  TextView(APIView):
    def get(self,request,*args,**kwargs):
        vertion = request.vertion
        return Httpresponse("成功")

版本传参有两种方式:第一种在url中的?后边传版本,使用QueryParameterVersioning这个类

          第二种在url中传版本:使用URLPathVersioning 这个类

序列化

由于queryset不能被json序列化,所以我们要整理下数据,因为通常json后的数据格式是这样的,列表中套字典

 
[
  {
    "title": "python",
    "price": 123
  },
  {
    "title": "php",
    "price": 233
  },
  {
    "title": "GO",
    "price": 33
  }
] 
 

方式一list强转

注意: json.dumps(data,ensure_ascii=False) 可以解决页面上中文乱码的问题.

 
# Create your views here.
from django.views import View
from api_demo.models import *
import json
#queryset 不能被json序列化
class BookView(View):
    def get(self,request,*args,**kwargs):
        booklist=list(Book.objects.all().values("title","price"))
        return HttpResponse(json.dumps(booklist))
 

方式二拼凑格式

 
from django.shortcuts import render,HttpResponse

# Create your views here.
from django.views import View
from api_demo.models import *
import json
class BookView(View):
    def get(self,request,*args,**kwargs):
        booklist=Book.objects.all()
        temp=[]
        for book in booklist:
            temp.append({
                "title":book.title,
                "price":book.price
                
            })
        return HttpResponse(json.dumps(temp))
 

方式三:Django的序列化工具serializers

关于Django中的序列化主要应用在将数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为Json格式。

 
from django.shortcuts import render,HttpResponse
from django.core import serializers #导入序列化
from django.views import View
from api_demo.models import *


class BookView(View):
    def get(self,request,*args,**kwargs):
        booklist=Book.objects.all()
        temp=serializers.serialize("json",booklist)
        return HttpResponse(temp)
 

这样得到是所有字段的信息

结果:

 View Code

[
{
"model": "api_demo.book",
"pk": 1,
"fields": {
"title": "python",
"price": 123,
"pub_date": null,
"publish": 1,
"authors": [
1,
]
}
},
{
"model": "api_demo.book",
"pk": 2,
"fields": {
"title": "php",
"price": 233,
"pub_date": null,
"publish": 2,
"authors": [
]
}
},
{
"model": "api_demo.book",
"pk": 3,
"fields": {
"title": "GO",
"price": 33,
"pub_date": null,
"publish": 2,
"authors": [
1,
]
}
}
]

以上三种的缺点: 尽管能把数据json序列化,但是不能json反序列化,这时候就出现了第四种方法

方式4.restframwork专门处理序列化的组件:serializers组件

 
from rest_framework.response import Response #引入restframework自己的Response
from rest_framework.views import APIView #引入 APIView
from rest_framework import serializers #用rest_framework自己的serializers
from api_demo.models import *


class Bookserializers(serializers.Serializer):
    """
    为book表建立序列化组件
    """
    title=serializers.CharField(max_length=32)
    price=serializers.IntegerField()


class BookView(APIView):#注意这里使用的是APIView不是View,如果是View不能用restframe的序列化
    
    def get(self,request,*args,**kwargs):
        booklist=Book.objects.all()
        temp=Bookserializers(booklist,many=True)#如果传入的是多个值,由于queryset是多个对象的集合,many=True,默认False
        print(">>>>",temp)
        print("-------",temp.data) #调用静态方法data,得到的是一种orderDict数据类型的数据
        return Response(temp.data) #必须要用rest_framework的Response发送,因为还要对data数据进行处理,发送其中的data就可以
 

结果:

>>>> Bookserializers(<QuerySet [<Book: python>, <Book: php>, <Book: GO>]>, many=True):
    title = CharField(max_length=32)
    price = IntegerField()
------- [OrderedDict([('title', 'python'), ('price', 123)]), OrderedDict([('title', 'php'), ('price', 233)]), OrderedDict([('title', 'GO'), ('price', 33)])]
原文地址:https://www.cnblogs.com/xyhh/p/10931383.html