python - 如何在 Django 中下载临时文件?

标签 python django django-rest-framework httpresponse content-disposition

我正在学习如何在 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也很有帮助,但我无法让它工作,也不知道如何测试它。我不确定移动到 apache 或其他东西是否合适,因为我有用户权限问题,并且这些文件在下载后会立即删除。我检查过“gcode”是目录 url,gcode content_type 应该是 text/plain。所以基本上,我怎样才能真正下载我的回复?

编辑1

这是完整的代码,而不仅仅是有问题的部分。

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 错误。

最佳答案

为了测试,您可以创建这样的 View :

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)

在您的代码末尾,以确保您的文件已被读取。

关于python - 如何在 Django 中下载临时文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40338297/

相关文章:

Django 如何将自定义变量传递给上下文以在自定义管理模板中使用?

javascript - 调整 Django Rest 框架模板

django - 是否有任何 Django 包可以为谷歌云存储资源创建签名 url?

python - 如何在 Python 中放大图像轴?

Python:如何使用日志记录模块每天创建日志文件?

python - 使用 python xlrd 将 xlsx 文件的单列写入 csv

django - 在生产环境中通过 Django 发送 SMTP 电子邮件

python - tkinter 中带有 matplotlib 图的弹出窗口

python - 迪维希语 django-pisa pdf 的问题

Django Rest Framework,使嵌套关系超链接