0

I have a string file_id of my file that is stored in mongodb in a fs collection (GridFs).

I need to store the file as a mongoengine FileField in a Document, and then return the file to an endpoint ... so access the file's content, content_type etc.

I am not sure how to create a FileField instance with the GridFs string id? And is it possible to get the content and content_type from the FileField?

The tutorials that I have seen all involve creating the FileField by writing the contents to mongodb, the difference is my contents are already in the GridFs and I have the string id.

class Test(Document):
    file = FileField()

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

So far I have been able to create a GridFsProxy object using the id, and can read the file using this.

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

If i store the read() results of the GridFSProxy into the FileField(); it is stored in MongoDb as an ObjectID and then later when I retrieve the object I don't seem to be able to get the content_type of the file. I need the content_type as it is important for how I return the file contents.

I'm not sure how to create the FileField using just the file_id and then use it when i retrieve the Document.

Any insight into using the FileField (and GridFSProxy) will be helpful.

RYS221
  • 60
  • 9

1 Answers1

0

The FileField is basically just a reference (ObjectId) pointing to the actual grid fs documents (stored in fs.chunks/fs.files). Accessing the content_type should be straightforward, you shouldn't have to use the GridFSProxy class at all, see below:

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()
bagerard
  • 5,681
  • 3
  • 24
  • 48