[英]Why won't this django-rest-swagger API documentation display/work properly?
我已經構建了一個Django API,當通過POST給出一個電子郵件地址時,將使用一個布爾值來響應,表明我的數據庫中已存在該電子郵件地址的天氣:
class isEmailTaken(views.APIView):
permission_classes = [permissions.AllowAny,]
def post(self, request, *args, **kwargs):
try:
email = request.DATA['email']
except KeyError:
return HttpResponse(
'An email was not given with this request.',
status=status.HTTP_400_BAD_REQUEST,
)
return HttpResponse(
json.dumps(
User.objects.filter(email=email),
content_type="application/json",
status=status.HTTP_200_OK,
)
)
現在我想使用django-rest-swagger包自動生成此API的文檔。 我安裝了軟件包並在三引號之間插入了您在上面看到的注釋。 當我查看django-rest-swagger為此API生成的文檔時,我會看到下面的圖片。
但是,當我點擊Try it out!
按鈕,我收到如下所示的錯誤。 值得注意的是,它從未讓我有機會輸入它應該通過POST發送的電子郵件參數。
為什么Django-Swagger-Package不創建允許我通過POST正確地使用“email”參數的文檔? 我該如何工作?
我使用由django-rest-swagger制作的cigar_example
測試了這個,在那個例子中,他們編寫了一個自定義視圖 ,它也沒有渲染輸入參數
最后我查看源代碼,發現django-rest-swagger需要get_serializer_class
來構建body參數
所以它使用以下代碼:
class isEmailTaken(views.APIView):
permission_classes = [permissions.AllowAny,]
serializer_class = IsEmailTakenSerializer
def get_serializer_class(self):
return self.serializer_class
def post(self, request, *args, **kwargs):
try:
email = request.DATA['email']
except KeyError:
return HttpResponse(
'An email was not given with this request.',
status=status.HTTP_400_BAD_REQUEST,
)
return HttpResponse(
json.dumps(
User.objects.filter(email=email),
content_type="application/json",
status=status.HTTP_200_OK,
)
)
和IsEmailTakenSerializer
:
from rest_framework import serializers
class IsEmailTakenSerializer(serializers.Serializer):
email = serializers.EmailField()
django-rest-swagger嘗試發送沒有數據的POST請求。
首先,你必須像這樣修復你的觀點:
from rest_framework import status
from django.http import HttpResponse
import json
def post(self, request, *args, **kwargs):
try:
email = request.DATA['email']
except KeyError:
return HttpResponse(
'An email was not given with this request.',
status=status.HTTP_400_BAD_REQUEST,
)
return HttpResponse(
json.dumps(
User.objects.filter(email=email),
content_type="application/json",
status=status.HTTP_200_OK,
)
)
如果你試試這個,你現在應該看到你的錯誤信息。
下一步是查看django-rest-swagger文檔以找出要做的事情,它會在“試一試”按鈕上方呈現一個html表單字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.