Upload and Download File From Mongo Using Bottle and Flask
Join the DZone community and get the full member experience.
Join For FreeIf you have a requirement to save and serve files, then there are at least a couple options.
- Save the file onto the server and serve it from there.
- Mongo1 provide GridFS2 store that allows you not only to store files but also metadata related to the file. For example: you can store author, tags, group etc right with the file. You can provide this functionality via option 1 too, but you would need to make your own tables and link the files to the metadata information. Besides replication of data is in built in Mongo.
Bottle
You can upload and download mongo files using Bottle3 like so:
import json
from bottle import run, Bottle, request, response
from gridfs import GridFS
from pymongo import MongoClient
FILE_API = Bottle()
MONGO_CLIENT = MongoClient('mongodb://localhost:27017/')
DB = MONGO_CLIENT['TestDB']
GRID_FS = GridFS(DB)
@FILE_API.put('/upload/< file_name>')
def upload(file_name):
response.content_type = 'application/json'
with GRID_FS.new_file(filename=file_name) as fp:
fp.write(request.body)
file_id = fp._id
if GRID_FS.find_one(file_id) is not None:
return json.dumps({'status': 'File saved successfully'})
else:
response.status = 500
return json.dumps({'status': 'Error occurred while saving file.'})
@FILE_API.get('/download/< file_name>')
def index(file_name):
grid_fs_file = GRID_FS.find_one({'filename': file_name})
response.headers['Content-Type'] = 'application/octet-stream'
response.headers["Content-Disposition"] = "attachment; filename={}".format(file_name)
return grid_fs_file
run(app=FILE_API, host='localhost', port=8080)
And here's the break down of the code:
Upload method:
Line 12: Sets up upload
method to recieve a PUT
request for /upload/<file_name>
url.
Line 15-17: Create a new GridFS file with file_name
and get the content from request.body
. request.body
may be StringIO
type or a File
type because Python is smart enough to decipher the body
type based on the content.
Line 18-19: If we can find the file by file name then it was saved successfully and therefore return a success response.
Line 20-22: Return error if file was not saved successfully.
Download method:
Line 27: Find the GridFS file.
Line 28-29: Set the response Content-Type
as application-octet-stream
and Content-Disposition
to attachment; filename=<file_name>
Line 31: Return the GridOut
object. Based on Bottle documentation below we can return an object which has .read()
method available and Bottle understands that to be a File
object.
File objects Everything that has a .read() method is treated as a file or file-like object and passed to the wsgi.file_wrapper callable defined by the WSGI server framework. Some WSGI server implementations can make use of optimized system calls (sendfile) to transmit files more efficiently. In other cases this just iterates over chunks that fit into memory.
And we are done (as far as Bottle is concerned).
Flask
You can upload/download files using Flask4 like so:
import json
from gridfs import GridFS
from pymongo import MongoClient
from flask import Flask, make_response
from flask import request
__author__ = 'ravihasija'
app = Flask(__name__)
mongo_client = MongoClient('mongodb://localhost:27017/')
db = mongo_client['TestDB']
grid_fs = GridFS(db)
@app.route('/upload/', methods=['PUT'])
def upload(file_name):
with grid_fs.new_file(filename=file_name) as fp:
fp.write(request.data)
file_id = fp._id
if grid_fs.find_one(file_id) is not None:
return json.dumps({'status': 'File saved successfully'}), 200
else:
return json.dumps({'status': 'Error occurred while saving file.'}), 500
@app.route('/download/')
def index(file_name):
grid_fs_file = grid_fs.find_one({'filename': file_name})
response = make_response(grid_fs_file.read())
response.headers['Content-Type'] = 'application/octet-stream'
response.headers["Content-Disposition"] = "attachment; filename={}".format(file_name)
return response
app.run(host="localhost", port=8081)
The Flask upload and download code is very similar to Bottle. It differs only in a few places detailed below:
Line 14: Routing is configured differently in Flask. You mention the URL and the methods that apply for that URL.
Line 17: Instead of request.body
you use request.data
Line 28-31: Make the response with the file content and set up the appropriate headers. Finally, return the response object.
Questions? Thoughts? Please feel free to leave me a comment below. Thank you for your time.
Github repo: https://github.com/RaviH/file-upload-download-mongo
References:
- MongoDB: http://www.mongodb.org/↩
- GridFS: http://docs.mongodb.org/manual/core/gridfs/↩
- Bottle: http://bottlepy.org/docs/dev/tutorial.html↩
- Flask: http://flask.pocoo.org/↩
- PyMongo GridFS doc http://api.mongodb.org/python/current/api/gridfs/index.html?highlight=gridfs#module-gridfs↩
- Get to know GridFS: https://dzone.com/articles/get-know-gridfs-mongodb↩
Published at DZone with permission of Ravi Isnab, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments