django框架配置swagger以及自定義參數(shù)使用方式
1.初步了解swagger
Swagger 是一個規(guī)范且完整的框架,用于生成、描述、調(diào)用和可視化 RESTful 風格的 Web 服務(wù)。
Swagger 的目標是對 REST API 定義一個標準且和語言無關(guān)的接口,可以讓人和計算機擁有無須訪問源碼、文檔或網(wǎng)絡(luò)流量監(jiān)測就可以發(fā)現(xiàn)和理解服務(wù)的能力。
當通過 Swagger 進行正確定義,用戶可以理解遠程服務(wù)并使用最少實現(xiàn)邏輯與遠程服務(wù)進行交互。
與為底層編程所實現(xiàn)的接口類似,Swagger 消除了調(diào)用服務(wù)時可能會有的猜測。
2.swagger優(yōu)勢
Swagger 的優(yōu)勢
- 支持 API 自動生成同步的在線文檔:使用 Swagger 后可以直接通過代碼生成文檔,不再需要自己手動編寫接口文檔了,對程序員來說非常方便,可以節(jié)約寫文檔的時間去學習新技術(shù)。
- 提供 Web 頁面在線測試 API:光有文檔還不夠,Swagger 生成的文檔還支持在線測試。參數(shù)和格式都定好了,直接在界面上輸入?yún)?shù)對應(yīng)的值即可在線測試接口。
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',
# 注冊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請求參數(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='商品價格'),
'count': openapi.Schema(type=openapi.TYPE_STRING, description='商品數(shù)量'),
'stock': openapi.Schema(type=openapi.TYPE_STRING, description='商品庫存'),
'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": "長度過長", 'code': 400})
if len(title) > 200:
return Response({'msg': '長度過長', '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ù)請求寫法 作為參考(思路是這樣)
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()
# 實例化分頁對象
page_cursor = LargeResultsSetPagination()
# 分頁
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é)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
np.where()[0] 和 np.where()[1]的具體使用
這篇文章主要介紹了np.where()[0] 和 np.where()[1]的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03
基于Python socket實現(xiàn)簡易網(wǎng)絡(luò)聊天室
本文主要介紹了基于Python socket實現(xiàn)簡易網(wǎng)絡(luò)聊天室,本文將通過pyqt5作為桌面應(yīng)用框架,socket作為網(wǎng)絡(luò)編程的框架,從而實現(xiàn)包括客戶端和服務(wù)端的網(wǎng)絡(luò)聊天室的GUI應(yīng)用,需要的可以參考一下2022-07-07
Python內(nèi)置函數(shù)property()如何使用
這篇文章主要介紹了Python內(nèi)置函數(shù)property()如何使用,幫助大家更好的理解和學習python,感興趣的朋友可以了解下2020-09-09

