我创建了一个API,该API允许我使用POSTMAN中的POST方法上传图像。提交后,我想在发出GET请求后显示该图像名称。 我没有使用任何型号 ,并且我无意从存储在其中的目录中获取图像;因为稍后我将在服务器中上传图片。
这是我目前的当前代码,但未成功:
views.py:
class API(APIView):
parser_classes = (MultiPartParser,)
def get(self, request, *args, **kwargs):
name = self.request.GET.get('image')
if name:
return Response({"img_name": name}, status=200)
return Response({"img_name" : None}, status = 400)
def post(self, request):
file = self.request.data
img_file = file['image'] #store the image data in this variable
if img_file:
uploaded_file = img_file
img = [{"image_name": uploaded_file}]
serializer = ImgSerializer(img, many = True).data
return Response(serializer, status = 200)
else:
return Response("Please upload", status = 400)
serializers.py:
from rest_framework import serializers
class ImgSerializer(serializers.Serializer):
image_name = serializers.CharField()
我在GET请求中的预期结果应该是这样的:
{'image_name' : 'image_name_from_POST_Request'}
但是我得到的却是这个结果:
None
如何使用Django的rest框架将数据从POST请求传递到GET请求?是否有一种无需使用模型即可部署此需求的有效方法?
答案 0 :(得分:0)
我知道了。我只是在POST方法中创建了一个JSON文件,并将必要的数据存储在其中。最后,为了查看GET方法中的数据,我打开了文件并将其作为响应返回。
views.py:
class API(APIView):
parser_classes = (MultiPartParser,)
def get(self, request):
with open('data.txt') as json_file:
data = json.load(json_file)
if data:
return Response(data, status=200)
return Response({"name" : None}, status = 400)
def post(self, request):
posted_file = self.request.data
img_file = posted_file['image']
if img_file:
uploaded_file = img_file
data = [{"image_name": uploaded_file}]
json_data = {"image_name": uploaded_file}
data = {}
data['key'] = []
data['key'].append(json_data)
with open('data.txt', 'w') as outfile:
json.dump(image, outfile)
serializer = ImgSerializer(image, many = True).data
return Response(serializer, status = 200)
else:
return Response(serializer.errors, status = 400)