【问题标题】:Create a Mongoengine FileField from a GridFs file_id or GridFSProxy从 GridFs file_id 或 GridFSProxy 创建 Mongoengine FileField
【发布时间】:2019-10-01 00:28:49
【问题描述】:

我的文件的字符串 file_id 存储在 fs 集合 (GridFs) 中的 mongodb 中。

我需要将文件作为 mongoengine FileField 存储在 Document 中,然后将文件返回到端点......因此访问文件的内容、content_type 等。

我不确定如何使用 GridFs 字符串 id 创建 FileField 实例?是否可以从 FileField 中获取 content 和 content_type?

我看到的教程都涉及通过将内容写入mongodb来创建FileField,不同之处在于我的内容已经在GridFs中并且我有字符串id。

class Test(Document):
    file = FileField()

test = Test()
test.upload.put(image_file, content_type='image/png')

到目前为止,我已经能够使用 id 创建一个 GridFsProxy 对象,并且可以使用它来读取文件。

class Test(Document):
    file = FileField()
    file_id = StringField() # bb2832e0-2ca4-44bc-8b1b-e01a77003b92

file_proxy = GridFSProxy(Test.file_id)
file_proxy.read() # Gives me the file content
file_proxy.get(file_id).content_type #can return name, length etc.

test = Test()
test.file = file_proxy.read() # in mongodb I see it as an ObjectID

如果我将 GridFSProxy 的 read() 结果存储到 FileField() 中;它作为 ObjectID 存储在 MongoDb 中,然后当我检索对象时,我似乎无法获取文件的 content_type。 我需要 content_type,因为它对于我如何返回文件内容很重要。

我不确定如何仅使用 file_id 创建 FileField,然后在检索文档时使用它。

对使用 FileField(和 GridFSProxy)的任何见解都会有所帮助。

【问题讨论】:

    标签: python mongodb schema mongoengine


    【解决方案1】:

    FileField 基本上只是一个引用 (ObjectId),指向实际的网格 fs 文档(存储在 fs.chunks/fs.files 中)。访问 content_type 应该很简单,您根本不必使用 GridFSProxy 类,见下文:

    from mongoengine import *
    
    class Test(Document):
        file = FileField()
    
    test = Test()
    image_bytes = open("path/to/image.png", "rb")
    test.file.put(image_bytes, content_type='image/png', filename='test123.png')
    test.save()
    
    Test.objects.as_pymongo()   # [{u'_id': ObjectId('5cdac41d992db9bfcaa870df'), u'file': ObjectId('5cdac419992db9bfcaa870dd')}]
    
    t = Test.objects.first()
    t.file              # <GridFSProxy: 5cdac419992db9bfcaa870dd>
    t.file.content_type     # 'image/png'
    t.file.filename         # 'test123.png'
    content = t.file.read()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 2013-03-29
      • 2013-04-25
      • 1970-01-01
      • 2019-09-24
      • 2016-06-19
      • 2016-12-24
      相关资源
      最近更新 更多