django框架配置swagger以及自定义参数使用方式

 更新时间:2023年11月24日 09:06:19   作者:Li- Li  
这篇文章主要介绍了django框架配置swagger以及自定义参数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

1.初步了解swagger

Swagger 是一个规范且完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

Swagger 的目标是对 REST API 定义一个标准且和语言无关的接口,可以让人和计算机拥有无须访问源码、文档或网络流量监测就可以发现和理解服务的能力。

当通过 Swagger 进行正确定义,用户可以理解远程服务并使用最少实现逻辑与远程服务进行交互。

与为底层编程所实现的接口类似,Swagger 消除了调用服务时可能会有的猜测。

2.swagger优势

Swagger 的优势

  • 支持 API 自动生成同步的在线文档:使用 Swagger 后可以直接通过代码生成文档,不再需要自己手动编写接口文档了,对程序员来说非常方便,可以节约写文档的时间去学习新技术。
  • 提供 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入门基础之数字字符串与列表

    Python入门基础之数字字符串与列表

    这篇文章主要给大家介绍了关于Python入门基础之数字字符串与列表的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-02-02
  • Python3爬虫带上cookie的实例代码

    Python3爬虫带上cookie的实例代码

    在本篇文章里小编给各位分享的是一篇关于Python3爬虫带上cookie的实例代码内容,需要的朋友们可以学习下。
    2020-07-07
  • 浅谈dataframe两列相乘构造新特征

    浅谈dataframe两列相乘构造新特征

    这篇文章主要介绍了dataframe两列相乘构造新特征,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-05-05
  • Spark处理数据排序问题如何避免OOM

    Spark处理数据排序问题如何避免OOM

    这篇文章主要介绍了Spark处理数据排序问题如何避免OOM,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05
  • Python利用ElementTree模块处理XML的方法详解

    Python利用ElementTree模块处理XML的方法详解

    ElementTree是python的XML处理模块,它提供了一个轻量级的对象模,下面这篇文章就来给大家介绍了关于Python利用ElementTree模块处理XML的方法,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-08-08
  • NumPy索引与切片的用法示例总结

    NumPy索引与切片的用法示例总结

    numpy 数组索引是一个大话题,有很多种方式可以让你选中数据的子集或某个单个元素,一维数组比较简单,看起来和 python 的列表很类似,这篇文章主要给大家介绍了关于NumPy索引与切片用法的相关资料,需要的朋友可以参考下
    2021-07-07
  • Python enumerate()计数器简化循环

    Python enumerate()计数器简化循环

    这篇文章主要介绍了Python enumerate()计数器简化循环,enumerate()最大的优点就是它返回一个带有计数器和值的元组,因此我们不必自己增加计数器,下面就来看看文章具体对它的详细介绍吧,需要的朋友可以参考一下
    2021-12-12
  • python实现读取类别频数数据画水平条形图案例

    python实现读取类别频数数据画水平条形图案例

    这篇文章主要介绍了python实现读取类别频数数据画水平条形图案例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-04-04
  • python使用心得之获得github代码库列表

    python使用心得之获得github代码库列表

    最近接了个项目,要求获得github的repo的api,度娘了一下,有不少文章介绍,总结了本文,分享给大家并附上代码
    2014-06-06
  • python中WSGI是什么,Python应用WSGI详解

    python中WSGI是什么,Python应用WSGI详解

    这篇文章主要介绍一下python中的WSGI, 小编在网上找了几篇非常好的关于WSGI介绍,整理一下分享给大家。
    2017-11-11

最新评论