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

时间:2021-09-29 16:45:54

I'm learning how to serve temporary files in Django, and even after reading the docs I'm having some trouble finishing it all up. These files are dynamically generated temporarily from user input.

我正在学习如何在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

The code above should place my temporary-gcode file from my server into an HttpResponse object, and the return function should download the file. It even slows down like its downloading, but there is no file once it's finished.

上面的代码应该将我的临时gcode文件从服务器放到一个HttpResponse对象中,返回函数应该下载这个文件。它甚至会像下载一样慢下来,但是一旦完成就没有文件了。

This question provided most of the useful info and this one was helpful as well, but I can't get it working and don't know how else to test it. I'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 checked that "gcode" is the directory url, and gcode content_type should be text/plain. So basically, how can I make my response actually download?

这个问题提供了大部分有用的信息,这个问题也很有用,但是我不能让它工作,也不知道如何测试它。我不确定迁移到apache或其他什么地方是否合适,因为我有用户权限问题,这些文件在下载后立即被删除。我检查过“gcode”是目录url, gcode content_type应该是文本/纯文本。基本上,我怎么才能让我的回复下载下来呢?

Edit1

Edit1

Here is the full code, not just the problematic section.

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

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

I'm using Django Rest Framework and trying to create a dynamic response from my API get request to react to parameters given in the URL. So I send a get request passing variables as parameters, it creates a file based on those variables, and lastly sends back the created file. All of this already works except the actual file download at the end. The get request returns an HTTP 500 error.

我正在使用Django Rest框架,并试图从我的API get请求创建一个动态响应来响应URL中给定的参数。所以我发送一个get请求作为参数传递变量,它基于这些变量创建一个文件,最后返回创建的文件。除了最后的实际文件下载之外,所有这些都已经开始工作了。get请求返回一个HTTP 500错误。

2 个解决方案

#1


1  

For test, you can create view like that:

对于测试,您可以创建这样的视图:

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

If you test in shell (django):

如果您在shell中测试(django):

print(response.content)

At end of your code to ensure that your file has been read.

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

#2


0  

From some additional research here it seems that since the get_query function is expecting a QuerySet, not a Response object. Thanks to the proposed testing methods above I know my issue is Django Rest Framework viewset, and outside the scope of the original question.

从这里的一些附加研究来看,由于get_query函数期望的是一个QuerySet,而不是一个响应对象。由于上面提出的测试方法,我知道我的问题是Django Rest框架视图集,超出了原始问题的范围。

#1


1  

For test, you can create view like that:

对于测试,您可以创建这样的视图:

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

If you test in shell (django):

如果您在shell中测试(django):

print(response.content)

At end of your code to ensure that your file has been read.

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

#2


0  

From some additional research here it seems that since the get_query function is expecting a QuerySet, not a Response object. Thanks to the proposed testing methods above I know my issue is Django Rest Framework viewset, and outside the scope of the original question.

从这里的一些附加研究来看,由于get_query函数期望的是一个QuerySet,而不是一个响应对象。由于上面提出的测试方法,我知道我的问题是Django Rest框架视图集,超出了原始问题的范围。