django文件下载问题

时间:2013-06-13 06:54:26

标签: python django amazon-s3 openstack openstack-swift

我有一些文件存储在OpenStack Swift(或任何其他存储系统)上。我的django应用程序提供基于浏览器的GUI,供用户从Swift后端下载这些文件:

(1) Each file will have a URL such as: http://domain.com/files/file1
(2) User could use browser or any other client program based on HTTP to download files.

我已经使用静态文件下载测试:

def download(request):
    try:
        #TODO
        file_name = 'E:/sample.docx'
        fsock = open(file_name,"r")
        mime_type_guess = mimetypes.guess_type(file_name)
        if mime_type_guess is not None:
            response = HttpResponse(fsock, mimetype=mime_type_guess[0])  
        response['Content-Length'] = os.path.getsize(file_name)         
        response['Content-Disposition'] = 'attachment; filename=' + file_name                        
    except IOError:
        response = HttpResponseNotFound()
    return response

我的问题是:

(1)我可以从下载视图下载文件,但下载的文件大小始终为1k。这有什么问题?

(2)我仍然不知道如何提供存储在其他Object Storage后端的动态文件下载,如OpenStack Swift?

1 个答案:

答案 0 :(得分:1)

首先,在Swift Storage中,上传的文件就像一个对象。您无法指定对象存储的文件路径。

其次,我们可以使用python-swiftclient下载上传的对象(文件)。示例代码在这里。

    def download(request):
        #Get object(file) using swiftclient
        url = str(request.values['url'])
        token = str(request.values['token'])
        container = str(request.values['container'])
        name = str(request.values['name'])
        header, data = Client.get_object(url, token, container, object_name)

        #Send object data to browser
        result = data
        response = Response(result)
        response.headers['Content-Type'] = content['header']['content-type']
        response.headers['Content-Disposition'] = 'attachment; filename="'+filename+'"'
        return response

希望这对你有所帮助。更多信息请访问http://docs.openstack.org/developer/python-swiftclient/swiftclient.html#swiftclient.client.get_object