如何使用pymongo从mongodb获取文件对象?

时间:2014-03-31 22:50:07

标签: python mongodb pymongo

我目前正在使用:

some_fs = gridfs.GridFS(db, "some.col")
fs_file = some_fs.get(index)

获取<class 'gridfs.grid_file.GridOut'>个对象。

如何获取文件对象或如何将其转换为python文件对象? 我是否必须保存为临时文件才能执行此操作?

编辑:

这是我正在使用的完整代码:

FFMPEG_BIN = "ffmpeg.exe"
some_fs = gridfs.GridFS(db, "some.col")
vid_id = ObjectId("5339e3b5b322631b544b2338")

vid_file = some_fs.get(vid_id)
raw =  vid_file.read()
print type(vid_file), type(raw)

with open(raw, "rb") as infile:
    pipe = sp.Popen([FFMPEG_BIN,
                 # "-v", "quiet",
                 "-y",
                 "-i", "-",
                 "-vcodec", "copy", "-acodec", "copy",
                 "-ss", "00:00:00", "-t", "00:00:10", "-sn",
                 "test.mp4" ]
                ,stdin=infile, stdout=sp.PIPE
)
pipe.wait()

输出:

[2014-03-31 19:03:00] Connected to DB.
<class 'gridfs.grid_file.GridOut'> <type 'str'>
Traceback (most recent call last):
  File "C:/dev/proj/src/lib/ffmpeg/win/test.py", line 19, in <module>
    with open(raw, "rb") as infile:
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

3 个答案:

答案 0 :(得分:0)

基于this documentation,您需要使用.read()方法。

我认为some_fs.get(index).read()会为您提供所需的信息。

答案 1 :(得分:0)

编辑:也许GridOut不是python file objects的正确实现。我的最后一个建议是尝试使用StringIO的内存文件。

import StringIO

FFMPEG_BIN = "ffmpeg.exe"
some_fs = gridfs.GridFS(db, "some.col")
vid_id = ObjectId("5339e3b5b322631b544b2338")

vid_file = some_fs.get(vid_id)

# Should be a proper file-like object
infile =  StringIO.StringIO(vid_file.read())

pipe = sp.Popen([FFMPEG_BIN,
    # "-v", "quiet",
    "-y",
    "-i", "-",
    "-vcodec", "copy", "-acodec", "copy",
    "-ss", "00:00:00", "-t", "00:00:10", "-sn",
    "test.mp4" ]
    ,stdin=infile, stdout=sp.PIPE
)
pipe.wait()

...

infile.close()

答案 2 :(得分:0)

  

这对我有用

FFMPEG_BIN = "ffmpeg.exe"
some_fs = gridfs.GridFS(db, "some.col")
vid_id = ObjectId("5339e3b5b322631b544b2338")

vid_file = some_fs.get(vid_id)

pipe = sp.Popen([FFMPEG_BIN,
    # "-v", "quiet",
    "-y",
    "-i", "-",
    "-vcodec", "copy", "-acodec", "copy",
    "-ss", "00:00:00", "-t", "00:00:10", "-sn",
    "test.mp4" ]
    ,stdin=sp.PIPE, stdout=sp.PIPE
)
pipe.stdin=vid_file.read()