如何在Django中使用POST方法创建的GET方法中查看API数据(无模型)?

时间:2019-11-19 11:12:10

标签: django django-rest-framework

我创建了一个DRF API,该API允许我通过POSTMAN使用POST方法提交图像。图像未存储在模型中。提交后,我想使用Django Rest Framework在浏览器中查看图像的名称。阅读网络中的资源后,我发现人们使用GET方法来查看模型中的所有数据。但是,我没有模型(暂时不需要),该如何实现此要求?

结果应该是这样的:

{
    "image_name": <"name_of_the_image_stored">
}

这是我到目前为止所做的:

from rest_framework.views import APIView
from rest_framework.response import Response 
from .serializers import ImgSerializer
from rest_framework import status
from rest_framework.parsers import FileUploadParser

class ImageAPI(APIView):
    parser_classes = (FileUploadParser,)
    def post(self, request):
        #key is 'image' when uploading in POSTMAN
        file = self.request.data
        data = file['image']
        if data:
            uploaded_file = data
            fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT)
            filename = fs.save(uploaded_file.name, uploaded_file)
            data = [{"image_name": filename}]  
            serializer = ImgSerializer(data, many = True).data
            return Response(serializer, status = 200)               
        else:
            return Response("Please upload an image", status = 400)

    def get(self, request):
         #What should I do here in order to view the submitted image above?

serializers.py:

from rest_framework import serializers

class ImgSerializer(serializers.Serializer):
    image_name = serializers.CharField()

urls.py:

from upload.views import ImageAPI
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    path("api/", ImageAPI.as_view(), name = "api"),
]
urlpatterns = format_suffix_patterns(urlpatterns)

1 个答案:

答案 0 :(得分:0)

首先,parser_classes应该是ImageAPI类的属性,因为我可以看到您已将其创建为局部变量,但不会执行您想要的操作。根据{{​​3}},request.data属性应该是一个字典,其中包含包含上载文件的单个键file。关于查看保存的图像,docs您可以找到一些方法来实现。

这是一个示例:

...
def get(self, request, *args, **kwargs):
    # here I assume you've sent the name of the image using query params, 
    # but there are other better ways to do that
    image_name = request.GET.get('image')

    # here you should read the file from your storage
    image_file = <read_image_file_by_given_name(image_name)>

    return HttpResponse(image_file, content_type='image/png')