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ǎng)絡(luò)流量監(jiān)測(cè)就可以發(fā)現(xiàn)和理解服務(wù)的能力。
當(dāng)通過 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 后可以直接通過代碼生成文檔,不再需要自己手動(dòng)編寫接口文檔了,對(duì)程序員來說非常方便,可以節(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)度過長(zhǎng)", 'code': 400}) if len(title) > 200: return Response({'msg': '長(zhǎng)度過長(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)文章
np.where()[0] 和 np.where()[1]的具體使用
這篇文章主要介紹了np.where()[0] 和 np.where()[1]的具體使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03對(duì)python 讀取線的shp文件實(shí)例詳解
今天小編就為大家分享一篇對(duì)python 讀取線的shp文件實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12Python設(shè)計(jì)模式之策略模式實(shí)例詳解
這篇文章主要介紹了Python設(shè)計(jì)模式之策略模式,結(jié)合實(shí)例形式分析了策略模式的概念、原理并結(jié)合實(shí)例形式分析了Python定義與使用策略模式相關(guān)操作技巧,需要的朋友可以參考下2019-01-01Python實(shí)現(xiàn)求數(shù)列和的方法示例
這篇文章主要介紹了Python實(shí)現(xiàn)求數(shù)列和的方法,涉及Python數(shù)值運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2018-01-01基于Python socket實(shí)現(xiàn)簡(jiǎn)易網(wǎng)絡(luò)聊天室
本文主要介紹了基于Python socket實(shí)現(xiàn)簡(jiǎn)易網(wǎng)絡(luò)聊天室,本文將通過pyqt5作為桌面應(yīng)用框架,socket作為網(wǎng)絡(luò)編程的框架,從而實(shí)現(xiàn)包括客戶端和服務(wù)端的網(wǎng)絡(luò)聊天室的GUI應(yīng)用,需要的可以參考一下2022-07-07Python內(nèi)置函數(shù)property()如何使用
這篇文章主要介紹了Python內(nèi)置函數(shù)property()如何使用,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下2020-09-09