django框架配置swagger以及自定義參數(shù)使用方式
1.初步了解swagger
Swagger 是一個(gè)規(guī)范且完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風(fēng)格的 Web 服務(wù)。
Swagger 的目標(biāo)是對(duì) REST API 定義一個(gè)標(biāo)準(zhǔn)且和語(yǔ)言無(wú)關(guān)的接口,可以讓人和計(jì)算機(jī)擁有無(wú)須訪問(wèn)源碼、文檔或網(wǎng)絡(luò)流量監(jiān)測(cè)就可以發(fā)現(xiàn)和理解服務(wù)的能力。
當(dāng)通過(guò) Swagger 進(jìn)行正確定義,用戶可以理解遠(yuǎn)程服務(wù)并使用最少實(shí)現(xiàn)邏輯與遠(yuǎn)程服務(wù)進(jìn)行交互。
與為底層編程所實(shí)現(xiàn)的接口類似,Swagger 消除了調(diào)用服務(wù)時(shí)可能會(huì)有的猜測(cè)。
2.swagger優(yōu)勢(shì)
Swagger 的優(yōu)勢(shì)
- 支持 API 自動(dòng)生成同步的在線文檔:使用 Swagger 后可以直接通過(guò)代碼生成文檔,不再需要自己手動(dòng)編寫接口文檔了,對(duì)程序員來(lái)說(shuō)非常方便,可以節(jié)約寫文檔的時(shí)間去學(xué)習(xí)新技術(shù)。
- 提供 Web 頁(yè)面在線測(cè)試 API:光有文檔還不夠,Swagger 生成的文檔還支持在線測(cè)試。參數(shù)和格式都定好了,直接在界面上輸入?yún)?shù)對(duì)應(yīng)的值即可在線測(cè)試接口。
3.django中的配置
3.1安裝drf-yasg2
pip install drf-yasg2
3.2settings.py配置
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'user',
# 注冊(cè)drf_yasg2
'drf_yasg2',<----這里
]3.3路由配置
from rest_framework import permissions
from drf_yasg2.views import get_schema_view
from drf_yasg2 import openapi
schema_view = get_schema_view(
openapi.Info(
title="Tweet API",
default_version='v1',
description="Welcome to the world of Tweet",
terms_of_service="https://www.tweet.org",
contact=openapi.Contact(email="demo@tweet.org"),
license=openapi.License(name="Awesome IP"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
from django.contrib import admin
from django.urls import path, include,re_path
from user import url
urlpatterns = [
re_path(r'^doc(?P<format>\.json|\.yaml)$',schema_view.without_ui(cache_timeout=0), name='schema-json'), #<-- 這里
path('doc/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), #<-- 這里
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), #<-- 這里
path('admin/', admin.site.urls),
path('user/', include(url)),
]然后使用 python manage.py runserver -----> http://127.0.0.1:8000/doc/
4.自定義參數(shù)的配置
post請(qǐng)求參數(shù)的寫法
body 傳參 TYPE_STIRING 字符串
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action
class AddGoods(APIView):
"""
添加商品
"""
request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
required=['sku_name', 'price', 'count', 'selling_price','count','stock','instruction','title'], properties=
{'sku_name': openapi.Schema(type=openapi.TYPE_STRING, description='商品名稱'),
'price': openapi.Schema(type=openapi.TYPE_STRING, description='商品價(jià)格'),
'count': openapi.Schema(type=openapi.TYPE_STRING, description='商品數(shù)量'),
'stock': openapi.Schema(type=openapi.TYPE_STRING, description='商品庫(kù)存'),
'instruction': openapi.Schema(type=openapi.TYPE_STRING, description='商品數(shù)量'),
'title': openapi.Schema(type=openapi.TYPE_STRING, description='商品數(shù)量')}
)
@swagger_auto_schema(method='post', request_body=request_body, )
@action(methods=['post'], detail=False, )
def post(self, request):
sku_name = request.data.get('sku_name')
price = request.data.get("price")
selling_price = request.data.get('selling_price')
title = request.data.get('title')
instruction = request.data.get('instruction')
count = request.data.get('count')
stock = request.data.get('stock')
# lock_count=request.data.get('lock_count')
if not all([sku_name, price, selling_price, title, instruction, count, stock]):
return Response({'msg': '添加信息不全', 'code': 400})
if len(sku_name) > 200:
return Response({"msg": "長(zhǎng)度過(guò)長(zhǎng)", 'code': 400})
if len(title) > 200:
return Response({'msg': '長(zhǎng)度過(guò)長(zhǎng)', 'code': 400})
Goods.objects.create(sku_name=sku_name, price=price,
selling_price=selling_price, title=title,
instruction=instruction, count=count, stock=stock)
return Response({'msg': '商品添加成功', 'code': 200})get 參數(shù)請(qǐng)求寫法 作為參考(思路是這樣)
params 傳參
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
class Look(APIViews):
query_param = openapi.Parameter(name='q', in_=openapi.IN_QUERY, description="查詢條件",
type=openapi.TYPE_STRING)
@swagger_auto_schema(method='get', manual_parameters=[query_param])
@action(methods=['get'], detail=False)
def get(self,request):
data=request.query_params
q=data.get('q')
if not q:
result_list =Goods.objects.order_by('-id').all()
else:
result_list=Goods.Objects.filter(Q(sku_name=q)|Q(dec=q)).order_by('-id')
total_count = result_list.count()
# 實(shí)例化分頁(yè)對(duì)象
page_cursor = LargeResultsSetPagination()
# 分頁(yè)
data_list = page_cursor.paginate_queryset(result_list, request, view=self)
data_list = self.get_serializer(data_list, many=True).data
result = {'code': 200, 'data': data_list, 'total_count': total_count}
return Response(result)總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
pycharm2024.3配置conda環(huán)境的問(wèn)題及解決方案
文章介紹了在PyCharm 2024.3中配置Conda環(huán)境的步驟,包括解決Conda環(huán)境安裝位置問(wèn)題、配置PyCharm解釋器以及解決終端無(wú)法自動(dòng)切換Conda環(huán)境的問(wèn)題2026-02-02
tensorflow 獲取checkpoint中的變量列表實(shí)例
今天小編就為大家分享一篇tensorflow 獲取checkpoint中的變量列表實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02
python使用win32com在百度空間插入html元素示例
這篇文章主要介紹了python使用win32com在百度空間插入html元素的示例,大家參考使用吧2014-02-02
使用Mac時(shí)psycopg2導(dǎo)入PyCharm失敗的解決
這篇文章主要介紹了使用Mac時(shí)psycopg2導(dǎo)入PyCharm失敗的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
python實(shí)現(xiàn)while循環(huán)打印星星的四種形狀
今天小編就為大家分享一篇python實(shí)現(xiàn)while循環(huán)打印星星的四種形狀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
Python中解決浮點(diǎn)數(shù)精度問(wèn)題的常見(jiàn)方法
在Python中,浮點(diǎn)數(shù)是以雙精度(64位)存儲(chǔ)的,這種表示方式雖然能夠表示非常廣泛的數(shù)值范圍,但并不能精確表示所有的小數(shù),下面我們來(lái)看看Python是如何解決浮點(diǎn)數(shù)精度問(wèn)題的吧2025-08-08
GitHub 熱門:Python 算法大全,Star 超過(guò) 2 萬(wàn)
4 月 27 日,GitHub 趨勢(shì)榜第 3 位是一個(gè)用 Python 編碼實(shí)現(xiàn)的算法庫(kù),Star 數(shù)早已達(dá)到 26000+2019-04-04
Pandas數(shù)據(jù)類型轉(zhuǎn)換df.astype()及數(shù)據(jù)類型查看df.dtypes的使用
Python,numpy都有自己的一套數(shù)據(jù)格式,本文主要介紹了Pandas數(shù)據(jù)類型轉(zhuǎn)換df.astype()及數(shù)據(jù)類型查看df.dtypes的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07

