gpt4 book ai didi

具有Swagger或其他文档的带有定义参数(request.POST)的Django Rest Framework自定义POST URL端点

转载 作者:行者123 更新时间:2023-12-03 16:18:14 25 4
gpt4 key购买 nike

先前在Django 1.11中,我以这种方式定义了Django REST API:
在url.py中

url(r'^api/test_token$', api.test_token, name='test_token'),
在api.py中
@api_view(['POST'])
def test_token(request):
# ----- YAML below for Swagger -----
"""
description: test_token
parameters:
- name: token
type: string
required: true
location: form
"""
token = request.POST['token']

return Response("test_token success", status=status.HTTP_200_OK)
现在,我正在迁移到Django 3.1.5,我想知道如何使用Django Rest Framework(DRF)以相同的方式实现上述目标。在上述特定情况下,POST API“test_token”采用一个参数。并生成诸如swagger/redoc之类的API文档(可用于测试API)
enter image description here
一些注意事项:
  • 在此还指出django-rest-swagger已于2019年6月弃用django-rest-swagger UI doesn't have form for POST request body (function based view)
  • 需要特别注意,它对参数https://www.django-rest-framework.org/tutorial/2-requests-and-responses/的使用request.POST(表单数据)
  • Django 1.11.x中的
  • 我正在使用此swagger_schema.py-https://gist.github.com/axilaris/b7152215a76f6f1f5ffca0436991328d

  • 如何在Django 3.x上实现此功能? (如标题中所示:具有Swagger或其他文档的已定义参数的Django Rest Framework自定义POST URL端点)
    更新:
    我认为这里有某种形式的解决方案:
    https://github.com/tfranzel/drf-spectacular/issues/279
    由于我有很多使用@api_view的API,因此更改docstring
    到装饰器@extend_schema可能是最简单的迁移路径。我希望有人可以使用@extend_schema在url.py上提供转换指导。这是为了实现URL端点和摇摇欲坠。谢谢。
    这是我与drf-spectacular最接近的
    @extend_schema( 
    parameters=[OpenApiParameter(
    name='token',
    type={'type': 'string'},
    location=OpenApiParameter.QUERY,
    required=False,
    style='form',
    explode=False,
    )],
    responses=OpenApiTypes.OBJECT,
    )
    @api_view(['POST'])
    def test_api(request):
    # ----- YAML below for Swagger -----
    """
    description: test_api
    parameters:
    - name: token
    type: string
    required: true
    location: form
    """
    token = request.POST['token']

    return Response("success test_api:" + token, status=status.HTTP_200_OK)
    它给这个(这是不正确的),请注意 token 查询
    curl -X POST "http://localhost:8000/api/test_token/?token=hello" -H  "accept: application/json" -H  "X-CSRFToken: JyPOSAQx04LK0aM8IUgUmkruALSNwRbeYDzUHBhCjtXafC3tnHRFsxvyg5SgMLhI" -d ""
    而不是POST输入参数(如何获得此参数?)
    curl -X POST --header 'Content-Type: application/x-www-form-urlencoded' --header 'Accept: application/json' --header 'X-CSRFToken: aExHCSwrRyStDiOhkk8Mztfth2sqonhTkUFaJbnXSFKXCynqzDQEzcRCAufYv6MC' -d 'token=hello' 'http://localhost:8000/api/test_token/
    解决方案:
    url.py
    from drf_yasg.utils import swagger_auto_schema 

    from rest_framework.response import Response
    from rest_framework import status

    from rest_framework.decorators import parser_classes
    from rest_framework.parsers import FormParser

    token = openapi.Parameter('token', openapi.IN_FORM, type=openapi.TYPE_STRING, required=True)
    something = openapi.Parameter('something', openapi.IN_FORM, type=openapi.TYPE_INTEGER, required=False)
    @swagger_auto_schema(
    method="post",
    manual_parameters=[token, something],
    operation_id="token_api"
    )
    @api_view(['POST'])
    # this is optional and insures that the view gets formdata
    @parser_classes([FormParser])
    def token_api(request):
    token = request.POST['token']
    something = request.POST['something']

    return Response("success test_api:" + token + something, status=status.HTTP_200_OK)


    schema_view = get_schema_view(
    openapi.Info(
    title="Snippets API",
    default_version='v1',
    description="Test description",
    terms_of_service="https://www.google.com/policies/terms/",
    contact=openapi.Contact(email="contact@snippets.local"),
    license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
    )


    urlpatterns = [

    path('token_api', token_api, name='token_api'),

    path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),

    ] + required_urlpatterns

    最佳答案

    如您所说,django-rest-swagger已过时。
    这就是为什么建议使用drf-yasg的原因。

    from drf_yasg import openapi
    from drf_yasg.utils import swagger_auto_schema

    class ArticleViewSet(viewsets.ModelViewSet):
    @swagger_auto_schema(request_body=openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
    'test_token': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
    }
    ))
    def create(self, request, *args, **kwargs):
    ...
    或者,如果您想使用DRF操作
        @swagger_auto_schema(method="post", request_body=openapi.Schema(
    type=openapi.TYPE_OBJECT,
    properties={
    'test_token': openapi.Schema(type=openapi.TYPE_STRING, description='string'),
    }
    ))
    @action(method=["post"], detail=False)
    def my_post_action(self, request, *args, **kwargs):
    ...
    或使用api View :
    # here we define that this view accepts a json (or object parameter) that has test_token parameter inside of it
    @swagger_auto_schema(method='post',
    request_body=openapi.Schema(
    type=openapi.TYPE_OBJECT, # object because the data is in json format
    properties={
    'test_token': openapi.Schema(type=openapi.TYPE_STRING, description='this test_token is used for...'),
    }
    ), operation_id="token_view")
    # your view
    @api_view(['POST'])
    def token_view(request):
    pass
    而且您的url.py看起来像这样
    # define some basic info about your api for swagger
    schema_view = get_schema_view(
    openapi.Info(
    title="Snippets API",
    default_version='v1',
    description="Test description",
    terms_of_service="https://www.google.com/policies/terms/",
    contact=openapi.Contact(email="contact@snippets.local"),
    license=openapi.License(name="BSD License"),
    ),
    public=True,
    permission_classes=[permissions.AllowAny],
    )

    urlpatterns = [
    # define your api view url
    path('token_view/', token_view),
    # define the url of the swagger ui
    url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    ]

    关于具有Swagger或其他文档的带有定义参数(request.POST)的Django Rest Framework自定义POST URL端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65918969/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com