Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Serve GridFs files from mongo engine with flask
from flask import Flask, request, redirect, url_for, make_response, abort
from mongoengine.fields import get_db
from bson import ObjectId
from gridfs import GridFS
from gridfs.errors import NoFile
from <your_app> import app
@app.route('/files/<oid>')
def serve_gridfs_file(oid):
try:
db = get_db()
gfs = GridFS(db)
fl = gfs.get(ObjectId(oid))
response = make_response(fl.read())
response.mimetype = fl.content_type
return response
except NoFile:
abort(404)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment