亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

django框架配置swagger以及自定義參數使用方式

 更新時間:2023年11月24日 09:06:19   作者:Li- Li  
這篇文章主要介紹了django框架配置swagger以及自定義參數使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

1.初步了解swagger

Swagger 是一個規(guī)范且完整的框架,用于生成、描述、調用和可視化 RESTful 風格的 Web 服務。

Swagger 的目標是對 REST API 定義一個標準且和語言無關的接口,可以讓人和計算機擁有無須訪問源碼、文檔或網絡流量監(jiān)測就可以發(fā)現和理解服務的能力。

當通過 Swagger 進行正確定義,用戶可以理解遠程服務并使用最少實現邏輯與遠程服務進行交互。

與為底層編程所實現的接口類似,Swagger 消除了調用服務時可能會有的猜測。

2.swagger優(yōu)勢

Swagger 的優(yōu)勢

  • 支持 API 自動生成同步的在線文檔:使用 Swagger 后可以直接通過代碼生成文檔,不再需要自己手動編寫接口文檔了,對程序員來說非常方便,可以節(jié)約寫文檔的時間去學習新技術。
  • 提供 Web 頁面在線測試 API:光有文檔還不夠,Swagger 生成的文檔還支持在線測試。參數和格式都定好了,直接在界面上輸入參數對應的值即可在線測試接口。

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.自定義參數的配置

post請求參數的寫法

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='商品數量'),
                                   'stock': openapi.Schema(type=openapi.TYPE_STRING, description='商品庫存'),
                                   'instruction': openapi.Schema(type=openapi.TYPE_STRING, description='商品數量'),
                                   'title': openapi.Schema(type=openapi.TYPE_STRING, description='商品數量')}
                                  )
 
    @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 參數請求寫法  作為參考(思路是這樣)

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)

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

  • 詳解在Python和IPython中使用Docker

    詳解在Python和IPython中使用Docker

    這篇文章主要介紹了詳解在Python和IPython中使用Docker,Docker是一個吸引人的新系統(tǒng),可以用來建立有趣的新技術應用,特別是云服務相關的,需要的朋友可以參考下
    2015-04-04
  • Python高級用法總結

    Python高級用法總結

    Python很棒,它有很多高級用法值得細細思索,學習使用。本文將根據日常使用,總結介紹Python的一組高級特性,包括:列表推導式、迭代器和生成器、裝飾器
    2018-05-05
  • np.where()[0] 和 np.where()[1]的具體使用

    np.where()[0] 和 np.where()[1]的具體使用

    這篇文章主要介紹了np.where()[0] 和 np.where()[1]的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • python在地圖上畫比例的實例詳解

    python在地圖上畫比例的實例詳解

    在本篇文章里小編給大家整理的是一篇關于如何用python在地圖上畫比例的相關實例內容,有興趣的朋友們可以學習下。
    2020-11-11
  • 對python 讀取線的shp文件實例詳解

    對python 讀取線的shp文件實例詳解

    今天小編就為大家分享一篇對python 讀取線的shp文件實例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • Python設計模式之策略模式實例詳解

    Python設計模式之策略模式實例詳解

    這篇文章主要介紹了Python設計模式之策略模式,結合實例形式分析了策略模式的概念、原理并結合實例形式分析了Python定義與使用策略模式相關操作技巧,需要的朋友可以參考下
    2019-01-01
  • Python實現求數列和的方法示例

    Python實現求數列和的方法示例

    這篇文章主要介紹了Python實現求數列和的方法,涉及Python數值運算相關操作技巧,需要的朋友可以參考下
    2018-01-01
  • 基于Python socket實現簡易網絡聊天室

    基于Python socket實現簡易網絡聊天室

    本文主要介紹了基于Python socket實現簡易網絡聊天室,本文將通過pyqt5作為桌面應用框架,socket作為網絡編程的框架,從而實現包括客戶端和服務端的網絡聊天室的GUI應用,需要的可以參考一下
    2022-07-07
  • Python類的繼承和多態(tài)代碼詳解

    Python類的繼承和多態(tài)代碼詳解

    這篇文章主要介紹了Python類的繼承和多態(tài)代碼詳解,具有一定借鑒價值,需要的朋友可以參考下
    2017-12-12
  • Python內置函數property()如何使用

    Python內置函數property()如何使用

    這篇文章主要介紹了Python內置函數property()如何使用,幫助大家更好的理解和學習python,感興趣的朋友可以了解下
    2020-09-09

最新評論