我想设计一个API来处理我的django媒体目录中的所有文件以响应GET请求 - 我的应用程序的view.py应该是什么样的?
答案 0 :(得分:0)
使用FileUploadParser解析原始文件上传内容。 request.data
属性将是一个包含上传文件的单个“文件”的字典。
class FileUploadView(views.APIView):
parser_classes = (FileUploadParser,)
def put(self, request, filename, format=None):
file_obj = request.FILES['file']
save_location = open(MEDIA_ROOT + file_obj.name, 'wb+')
for chunk in up_file.chunks():
save_location.write(chunk)
save_location.close()
return Response(status=204)
答案 1 :(得分:0)
功能基础代码
ufile = MODEL_NAME.objects.filter(user_id=user_id)
if ufile:
uf = ufile[0]
path = request.META['HTTP_HOST']
path1 = "http://" + path + settings.MEDIA_URL
url = path1 + str(uf.file).replace("./", "")
dd = {'file': url}
return Response(dd)
else:
return Response(message="no file")
答案 2 :(得分:0)
如果UR使用序列化器
#serializers.PY
class ProfileImageSerialiser(serializers.ModelSerializer):
class Meta:
model = MODEL_NAME
fields = ('FIELD1', 'FIELD2')
#views.py
class GetProfileImageViewSet(generics.ListAPIView):
serializer_class = ProfileImageSerialiser
def get_queryset(self):
user_id = self.kwargs['user_id']
image = MODEL_NAME.objects.filter(user_id=user_id)
return image