【问题标题】:django: Is there anyway to serve a file directly from memorydjango:无论如何直接从内存中提供文件
【发布时间】:2016-04-30 16:22:03
【问题描述】:

所以我有用户从 django 服务器请求他们的文件,其中一些进程在请求的文件上发生。目前我正在将文件写入磁盘并从那里提供服务。

是否可以将文件从内存中直接提供给用户以获得更好的效率和性能(使用 x-sendfile)?

这是我目前的看法:

def ServeSegment(request, segmentID):
    segments =[]
    obj = MainFile.objects.filter(owner=request.user)
    file_name = MainFile.objects.get(file_id=segmentID).file_name
    file_suffix = file_name = MainFile.objects.get(file_id=segmentID).file_suffix
    if request.method == 'GET':
        hosts = settings.HOSTS
        for i in hosts:
            try:
                url = 'http://' + i + ':8000/foo/'+str(segmentID)
                r = requests.get(url, timeout=1, stream=True)
                if r.status_code == 200:
                    segments.append(r.content)
            except:
                continue
        instance = SeIDA(filename='test', x=settings.M, y=settings.N)
        docfile = instance.decoder(segments)
        with open('/tmp/Files/'+file_name, 'wb') as f:
            f.write(docfile)
            response = HttpResponse()
            response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name)
            response['X-Sendfile'] = "/tmp/Files/{0}".format(file_name)
            return response

注意:使用 SeIDA 模块,将数据编码为 N 个片段,这样 M 个片段就足以构建数据。因此,在上面的视图中,我正在从存储服务器中检索段并将它们组合起来。

我的问题是:如何直接提供 docfile 而不保存它。到底有没有?

【问题讨论】:

标签: python django


【解决方案1】:

您不能使用 X-Sendfile 从内存中提供它,因为 Apache 运行在不同的进程中,即使在完全独立的机器上也是如此。

但是在这种情况下,使用 sendfile 并没有真正让事情变得更有效率。既然你说文件已经在内存中,你应该直接从那里提供它,而不需要通过 Apache:只需在响应中返回它。

docfile = instance.decoder(segments)
response = HttpResponse()
response.write(docfile)
response['Content-Disposition'] = 'attachment; filename={0}'.format(file_name)
return response

【讨论】:

  • 不知道我可以直接写信回复,谢谢你教我。这种方法是否适合处理请求文件的大量并发连接?
猜你喜欢
  • 2019-01-29
  • 2012-07-07
  • 2019-01-05
  • 2016-06-07
  • 1970-01-01
  • 2020-08-09
  • 2011-06-01
  • 1970-01-01
  • 2016-05-22
相关资源
最近更新 更多