我创建了一个简单的 html 页面,它允许我上传图像并将其存储在目录中,而无需使用模型。我的目标是使用 REST API 框架并显示在 REST API 中上传的特定图像,即
{"image": "uploaded_image_by_user"}
如何为此 REST API 创建 POST 和 GET 方法?
我尝试这样做,但它不能正常工作。有没有正确的方法来做到这一点?或者更确切地说,有人知道创建没有模型的 REST API 的基本方法吗?仅供参考,我是 Django 的新手
我目前的代码:
视图.py
from django.shortcuts import render
from django.db import models
from django.views.generic import View, TemplateView, CreateView
from image_app.forms import ImageForm
from django.contrib.messages.views import SuccessMessageMixin
import requests
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from image_app.serializers import ImageSerializer
from django.http import Http404
import os, sys
from rest_framework.parsers import FileUploadParser
from django.http import HttpResponseRedirect
from django.core.files.storage import FileSystemStorage
from django.conf import settings
from django.contrib import messages
class BaseView(TemplateView):
template_name = "base.html"
def upload(request):
if request.method == 'POST':
filename = rename()
uploaded_file = request.FILES['image']
fs = FileSystemStorage(location=settings.PRIVATE_STORAGE_ROOT)
name = fs.save(uploaded_file.name, uploaded_file)
messages.success(request, 'Uploaded Image Successfully.')
return HttpResponseRedirect("base.html")
return render(request, "insert_image.html")
class ImageList(APIView):
def get(self, request, format = None):
file = os.listdir(r'path_name_of_uploaded_image')[0]
print(file)
if file:
images = [{"similar_image": file}]
serializer = ImageSerializer(images, many = True).data
return Response({'serializer': serializer}, status = status.HTTP_201_CREATED)
else:
return Response({"similar_image": "Similar images are non existent"}, status = 400)
def post(self, request):
parser_classes = (FileUploadParser,)
file = request.data.get('image', None)
return Response({"similar_image": file}, status = 200)
序列化程序.py
from rest_framework import serializers
class ImageSerializer(serializers.Serializer):
similar_image = serializers.CharField()
使用ViewSets
并覆盖它的 get 和 post 方法https://www.django-rest-framework.org/api-guide/viewsets/
在urls.py
提供这个SomeViewSet.as_view({'get': 'list', 'post':'create'})
其中 get 和 posts 指的是 GET 和 POST 方法,而 list 和 create 指的是 ViewSet 中的函数
您不必在任何地方提及模型。
最后你可以有这样的东西 return JsonResponse({"image": "uploaded_image_by_user"})
JsonResponse 为 from django.http import JsonResponse
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句