我正在学习如何在Django中提供临时文件,即使在阅读了文档之后,我也遇到了一些困难。这些文件是从用户输入中临时生成的。
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对象中,并且返回函数应该下载这个文件。它甚至像下载一样慢下来,但是一旦它完成,就没有文件了。
这个问题提供了大部分有用的信息,这一个也很有用,但我无法让它正常工作,也不知道如何测试它。我不确定迁移到apache或其他地方是否合适,因为我有用户权限问题,这些文件在下载后立即删除。我已经检查过" gcode“是目录url,而gcode content_type应该是text/平原。基本上,我怎样才能让我的回应真正下载呢?
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框架,并试图从我的API请求中创建一个动态响应,以响应URL中给定的参数。因此,我发送一个get请求,将变量作为参数传递,它根据这些变量创建一个文件,最后将创建的文件发回。除了最后的实际文件下载之外,所有这些都可以工作。get请求返回HTTP 500错误。
发布于 2016-10-31 09:20:13
为了进行测试,您可以创建这样的视图:
def download_file(request):
gcode = "/home/bradman/Documents/Programming/DjangoWebProjects/3dprinceprod/fullprince/media/uploads/tmp/skull.gcode"
resp = HttpResponse('')
with open(gcode, 'r') as tmp:
filename = tmp.name.split('/')[-1]
resp = HttpResponse(tmp, content_type='application/text;charset=UTF-8')
resp['Content-Disposition'] = "attachment; filename=%s" % filename
return resp如果在shell (Django)中进行测试:
print(response.content)在代码的末尾,以确保您的文件已被读取。
发布于 2016-11-02 00:38:51
从其他一些研究这里中可以看出,由于get_query函数期望的是一个QuerySet,而不是响应对象。由于上面建议的测试方法,我知道我的问题是Django Rest Framework视图集,并且超出了最初问题的范围。
https://stackoverflow.com/questions/40338297
复制相似问题