我正在学习如何在Django中提供临时文件,甚至在阅读docs之后我还是遇到了一些麻烦 . 这些文件是从用户输入临时动态生成的 .
def get_queryset(self):
gcode = "/home/bradman/Documents/Programming/DjangoWebProjects/3dprinceprod/fullprince/media/uploads/tmp/skull.gcode"
test_file = open(gcode, 'r')
response = HttpResponse(test_file, content_type='text/plain')
response['Content-Disposition'] = "attachment; filename=%s.gcode" % title
print (response)
return response
上面的代码应该将我的临时gcode文件从我的服务器放入一个HttpResponse对象,返回函数应该下载该文件 . 它甚至会像下载一样慢下来,但一旦完成就没有文件 .
This question提供了大部分有用的信息,this one也很有帮助,但我可以_110413知道如何测试它 . 我'm not sure if moving to apache or something is appropriate since I have user permission issues and these files are immediately deleted after downloaded. I' ve检查"gcode"是目录url,gcode content_type应该是text / plain . 所以基本上,我怎样才能让我的回复真正下载?
Edit1
这是完整的代码,而不仅仅是有问题的部分 .
class SubFileViewSet(viewsets.ModelViewSet):
queryset = subfiles.objects.all()
serializer_class = SubFilesSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
def get_queryset(self):
req = self.request
make = req.query_params.get('make')
model = req.query_params.get('model')
plastic = req.query_params.get('plastic')
quality = req.query_params.get('qual')
filenum = req.query_params.get('fileid')
hotend = req.query_params.get('hotendtemp')
bed = req.query_params.get('bedtemp')
if make and model and plastic and quality and filenum:
filepath = subfiles.objects.values('STL', 'FileTitle').get(fileid = filenum)
path = filepath['STL']
title = filepath['FileTitle']
gcode = TheMagic(
make=make,
model=model,
plastic=plastic,
qual=quality,
path=path,
title=title,
hotendtemp=hotend,
bedtemp=bed)
test_file = open(gcode, 'r')
response = HttpResponse(test_file, content_type='text/plain')
response['Content-Disposition'] = "attachment; filename=%s.gcode" % title
print (response.content)
return response
else:
print ('normal or non complete download')
return self.queryset
我正在使用Django Rest Framework并尝试从我的API get请求创建动态响应,以响应URL中给出的参数 . 所以我发送一个get请求传递变量作为参数,它根据这些变量创建一个文件,最后发送回创建的文件 . 所有这些都已经有效,除了最后的实际文件下载 . get请求返回HTTP 500错误 .
2 回答
从一些额外的研究here看来,因为get_query函数期望一个QuerySet,而不是一个Response对象 . 感谢上面提出的测试方法,我知道我的问题是Django Rest Framework视图集,并且超出了原始问题的范围 .
对于测试,您可以创建如下视图:
如果你在shell中测试(django):
在代码的末尾,以确保您的文件已被读取 .