使用python从mongo gridfs下载文件

时间:2014-07-30 17:34:28

标签: mongodb

我已将文件上传到mongo.But当我想通过网络浏览器上的httpresonse从mongo下载时,这不起作用。

这是views.py:

    if filename is not None:
    file_ = db.fs.files.find_one({
    'filename':filename
        })
    file_id = file_['_id']
    wrapper = fs.get(file_id).read()

    response =  StreamingHttpResponse(FileWrapper(wrapper),content_type=file_['contentType'])

    response['Content-Disposition'] = 'attachment; filename=%s' % str(filename)
    response['Content-Length']      = file_['length'] 
    return response

我收到了这个错误:

Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
self.finish_response()
File "/usr/lib/python2.7/wsgiref/handlers.py", line 126, in finish_response
for data in self.result:
File "/usr/local/lib/python2.7/dist-packages/django/utils/six.py", line 473, in next
return type(self).__next__(self)
 File "/usr/local/lib/python2.7/dist-packages/django/http/response.py", line 292, in   __next__
return self.make_bytes(next(self._iterator))
 File "/usr/lib/python2.7/wsgiref/util.py", line 30, in next
data = self.filelike.read(self.blksize)
AttributeError: 'str' object has no attribute 'read'

但是当我将StreamingHttpResponse更改为HttpResponse时,错误如下:

[30/Jul/2014 17:29:43] "GET /download/cs101/ HTTP/1.1" 200 664
/usr/lib/python2.7/wsgiref/handlers.py:126: DeprecationWarning: 
 Creating streaming     responses with `HttpResponse` is deprecated.
 Use `StreamingHttpResponse`instead if you need the streaming behavior.
for data in self.result:

Traceback (most recent call last):
 File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run
   self.finish_response()
 File "/usr/lib/python2.7/wsgiref/handlers.py", line 126, in finish_response
for data in self.result:
 File "/usr/local/lib/python2.7/dist-packages/django/utils/six.py", line 473, in next
return type(self).__next__(self)
 File "/usr/local/lib/python2.7/dist-packages/django/http/response.py", line 292, in __next__
return self.make_bytes(next(self._iterator))
File "/usr/lib/python2.7/wsgiref/util.py", line 30, in next
data = self.filelike.read(self.blksize)
AttributeError: 'str' object has no attribute 'read'

提前致谢!

1 个答案:

答案 0 :(得分:1)

您正在调用read方法:

wrapper = fs.get(file_id).read()

所以你得到str(假设Python 2,如果是3,你得到bytes)。 FileWrapper需要像object这样的文件,当然str不是一个。

尝试使用:

wrapper = fs.get(file_id)

这将返回类似object的文件。

OTOH,pymongo' s .get()返回一个GridOut实例,该实例已经支持iteration,所以为什么不尝试以下内容:

wrapper = fs.get(file_id)
response =  StreamingHttpResponse(wrapper, content_type=file_['contentType'])