版本控制、序列化

版本控制有利於咱們根據客戶端的版本不一樣作出不一樣的處理,好比微信的版本不一樣php

url.pypython

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.pyweb

 
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這個類django

          第二種在url中傳版本:使用URLPathVersioning 這個類json

 

序列化api

因爲queryset不能被json序列化,因此咱們要整理下數據,由於一般json後的數據格式是這樣的,列表中套字典微信

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

方式一list強轉app

注意: 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)])]
相關文章
相關標籤/搜索