網站首頁 編程語言 正文
在前后端分離是大趨勢的背景下,前端獲取數據都是通過調用后臺的接口來獲取數據微服務的應用越來越多。Django是Python進行web應用開發常用的web框架,用Django框架進行web應用框架減少了很多工作,通常用很少量的代碼就可以實現數據的增、刪、改、查的業務應用,同樣用Django的restframework的框架對外發布接口也是非常的簡單方便,幾行代碼就可以將數據對象通過接口的方式提供服務。因為在實際開發過程中接口的返回數據有一定的格式,本文介紹通過自定義Response返回對象來自定義接口返回數據格式。
以下示例將數據對象Friend通過restframework框架進行接口發布。
只要定義Friend數據對象
class Friend(BaseModel):
id=models.AutoField(primary_key=True)
siteName=models.CharField(max_length=20, verbose_name='友鏈站點名稱')
path=models.CharField(max_length=100, verbose_name='地址路徑')
desc=models.CharField(max_length=200, verbose_name='描述')
def __str__(self):
return self.siteName
class Meta:
verbose_name='友鏈'
verbose_name_plural='友鏈'
定義一個序列化類將返回的字段序列化
class FriendModelSerializer(serializers.ModelSerializer):
class Meta:
model = Friend
fields = "__all__"
定義一個接口視圖類獲取數據
class FriendView(viewsets.ModelViewSet):
queryset = Friend.objects.all()
serializer_class = FriendModelSerializer
定義接口路由就可以通過httprestfull的接口進行訪問了
friend_list=views.FriendView.as_view({'get':'list',})
urlpatterns = [
path('friend/',friend_list),
]
接口訪問效果如下:
http://localhost:8000/api/friend/
但是在項目中經常會碰到接口格式變化的情況,restframework框架默認的返回數據格式不滿足應用的需求。比如一般的接口都會有接口返回的code、msg、data,code用來標識接口返回代碼比如200是正常,msg用來記錄異常或其信息,data用來返回具體的數據。
通過restframework接口自定義返回數據格式也是很簡單方便的。
先自定義Response返回對象,在返回對象中自定義數據返回的格式,示例代碼如下:
from rest_framework.response import Response
from rest_framework.serializers import Serializer
class CustomResponse(Response):
def __init__(self,data=None,code=None,msg=None,
status=None,
template_name=None, headers=None,
exception=False, content_type=None,**kwargs):
super().__init__(None, status=status)
if isinstance(data, Serializer):
msg = (
'You passed a Serializer instance as data, but '
'probably meant to pass serialized `.data` or '
'`.error`. representation.'
)
raise AssertionError(msg)
#自定義返回格式
self.data={'code':code,'msg':msg,'data':data}
self.data.update(kwargs)
self.template_name=template_name
self.exception=exception
self.content_type=content_type
if headers:
for name, value in headers.items():
self[name] = value
在接口接口視圖類獲取數據返回時,使用該自定義的Response返回對象。
class FriendView(viewsets.ModelViewSet):
queryset = Friend.objects.all()
serializer_class = FriendModelSerializer
#自定義list方法,自定義Response返回
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
return CustomResponse(data=serializer.data, code=200, msg="OK", status=status.HTTP_200_OK)
接口訪問效果如下:
可以看到返回數據格式中增加了code,msg 數據放到了data節點
列表數據通常接口要提供翻頁功能,在接口中要有總頁數、當前頁、是否有下一頁的信息。
可以自定義一個分頁器,在分頁器中自定義需要返回的分頁參數
參考示例代碼如下:
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from common.customresponse import CustomResponse
class MyPage(PageNumberPagination):
page_size = 8 #每頁顯示數量
max_page_size = 50 #每頁最大顯示數量。
page_size_query_param = 'size' #每頁數量的參數名稱
page_query_param = 'page' #頁碼的參數名稱
def get_paginated_response(self, data):
#自定義分頁器的返回參數
return CustomResponse(data=data,code=200,msg="OK",status=status.HTTP_200_OK, count=self.page.paginator.count,next=self.get_next_link(),previous=self.get_previous_link(),size=self.page_size,page=self.page.number)
在接口接口視圖類獲取數據返回時,如果有分頁器則使用該分頁器自定義的Response返回對象。
class FriendView(viewsets.ModelViewSet):
queryset = Friend.objects.all()
serializer_class = FriendModelSerializer
pagination_class = MyPage
#自定義list方法,自定義Response返回
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
#如果有分頁器,則進行分頁后返回
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return CustomResponse(data=serializer.data, code=200, msg="OK", status=status.HTTP_200_OK)
接口訪問效果如下:
可以看到接口中自定義增加了分頁信息。
但是有時候可能希望分頁的信息數據要放在data節點里面,這樣也是可以做到的。
from rest_framework import status
from rest_framework.pagination import PageNumberPagination
from common.customresponse import CustomResponse
class MyPage(PageNumberPagination):
page_size = 8 #每頁顯示數量
max_page_size = 50 #每頁最大顯示數量。
page_size_query_param = 'size' #每頁數量的參數名稱
page_query_param = 'page' #頁碼的參數名稱
#自定義分頁器的返回參數
def get_paginated_response(self, data):
ret_data = dict()
ret_data['items'] = data
# 加入自定義分頁信息
ret_data['total'] = self.page.paginator.count
ret_data['hasNextPage'] = self.get_next_link()
ret_data['size'] = self.page_size
ret_data['page'] = self.page.number
return CustomResponse(data=ret_data,code=200,msg="OK",status=status.HTTP_200_OK)
接口訪問效果如下:
可以看到接口中自定義增加了分頁信息,分頁的信息數據放在data節點里面了
至此,本文介紹了通過Django的restframework接口框架自定義Response返回對象來自定義返回數據格式。Django的restframework接口框架使用簡單方便,拿來即用,能夠很大程度上減少代碼開發量。
原文鏈接:https://blog.csdn.net/fullbug/article/details/125773730
相關推薦
- 2022-04-09 idea解決sun.misc.BASE64Encoder 類找不到報錯
- 2022-09-21 Android開發之AAR文件的生成與使用步驟_Android
- 2022-06-14 一文帶你搞懂Numpy中的深拷貝和淺拷貝_python
- 2022-09-12 IOS開發自定義view方法規范示例_IOS
- 2022-07-19 iptables限制docker端口禁止對某臺主機進行提供服務
- 2022-04-02 Python操作word文檔的示例詳解_python
- 2023-05-21 python?jinjia2的項目使用_python
- 2022-10-03 Docker啟動失敗報錯Failed?to?start?Docker?Application?Con
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支