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

1.初步了解swagger

2.swagger优势

3.django中的配置

3.1安装drf-yasg2

3.2settings.py配置

3.3路由配置

4.自定义参数的配置


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)
            

5.写到这就结束了,去写写吧,这是小编的写法,有什么疑问指出昂

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值