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

2024-09-30 12:18:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前正在使用:

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

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

如何获得一个file对象,或者如何将其转换为python文件对象? 我必须保存为临时文件才能执行此操作吗?在

编辑:

这是我使用的完整代码:

^{pr2}$

输出:

[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

Tags: 文件对象dbgetindexcolsomefs
3条回答

编辑:也许GridOut不是pythonfile 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()

This worked for me

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()

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

我认为some_fs.get(index).read()将满足您的需要。在

相关问题 更多 >

    热门问题