简体   繁体   中英

How to generate ping-pong api using Django Rest Framework?

I want to build a simple Ping-Pong using Django Rest Framework, so I don't need Model. I watch the api's status via swagger(drf_yasg), but I cannot find any parameters of it.

I want to create Serializer, View and some code for routing. And I got some error lines from terminal.

Serializer

from rest_framework import serializers


class PingPongSerializer(serializers.Serializer):
    ping = serializers.CharField(allow_blank=True,
                                 default="ping",
                                 max_length=20,
                                 help_text="please input 'ping'")

# example_ping = PingPongSerializer({"ping": "hoge"})
# => {'ping' : 'hoge'}
# example_ping = PingPongSerializer({})
# print(example_ping.data)
# => {'ping' : 'hoge'}

View

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from ping_pong.serializers import PingPongSerializer
# Create your views here.


class PingPongView(APIView):
    def get(self, request, format=None):
        serializer = PingPongSerializer(data=request)
        print(request)
        if serializer.is_valid():
            print(request.data)
            return Response(serializer.data)
        else:
            print(serializer)
            print(serializer.errors)
            return Response({'result': "I don't know anything"})

Urls

from django.contrib import admin
from django.urls import path

from django.conf.urls import url

from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

from rest_framework import routers
from ping_pong import views
from django.conf.urls import include

# router = routers.SimpleRouter()
# router.register(r'ping', views.PingPongView, base_name='ping')

schema_view = get_schema_view(
   openapi.Info(
      title="Restful API Lists",
      default_version='v1',
      description="Ping Pong",
      license=openapi.License(name="MIT"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)



urlpatterns = [
    path('admin/', admin.site.urls),
    # url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
   url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    url(r'ping', views.PingPongView.as_view(), name='ping'),
]

Results

curl

curl -X GET "http://localhost:8000/ping" -H  "accept: application/json" -H  "X-CSRFToken: ..."

result

{
  "result": "I don't know anything"
}

error log

<rest_framework.request.Request object at 0x7f2ed029d850>
PingPongSerializer(data=<rest_framework.request.Request object>):
    ping = CharField(allow_blank=True, default='ping', help_text="please input 'ping'", max_length=20)
{'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got Request.', code='i
nvalid')]}                                

Thanks to the advice I was able to find the answer.

The final code looks like this:

Serializer

from rest_framework import serializers


class PingPongSerializer(serializers.Serializer):
    ping = serializers.CharField(allow_blank=True,
                                 default="ping",
                                 max_length=10,
                                 help_text="please input 'ping'")

View

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from ping_pong.serializers import PingPongSerializer
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
# Create your views here.


class PingPongView(APIView):
    @swagger_auto_schema(manual_parameters=[
        openapi.Parameter('ping',
                          openapi.IN_QUERY,
                          description="please input ping",
                          type=openapi.TYPE_STRING)
    ])
    def get(self, request, format=None):
        serializer = PingPongSerializer(data=request.GET)
        if serializer.is_valid():
            if serializer.data['ping'] == 'ping':
                return Response({'result': 'pong'})
            else:
                return Response({'result': "What's in your head?"})
        else:
            return Response({'error': serializer.errors})

urls

from django.contrib import admin
from django.urls import path

from django.conf.urls import url

from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

from rest_framework import routers
from ping_pong import views
from django.conf.urls import include

router = routers.SimpleRouter()
router.register(r'ping', views.PingPongView, base_name='ping')

schema_view = get_schema_view(
   openapi.Info(
      title="Restful API Lists",
      default_version='v1',
      description="Ping Pong Api",
      license=openapi.License(name="MIT"),
   ),
   public=True,
   permission_classes=(permissions.AllowAny,),
)



urlpatterns = [
    path('admin/', admin.site.urls),
    # url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
   url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
    url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
    url(r'ping', views.PingPongView.as_view(), name='ping'),
]

Result

params : "ppng"

response : { "result": "What's in your head?" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM