Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Upload and Download File From Mongo Using Bottle and Flask

DZone's Guide to

Upload and Download File From Mongo Using Bottle and Flask

· Database Zone
Free Resource

Whether you work in SQL Server Management Studio or Visual Studio, Redgate tools integrate with your existing infrastructure, enabling you to align DevOps for your applications with DevOps for your SQL Server databases. Discover true Database DevOps, brought to you in partnership with Redgate.

If you have a requirement to save and serve files, then there are at least a couple options.

  1. Save the file onto the server and serve it from there.
  2. 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:

It’s easier than you think to extend DevOps practices to SQL Server with Redgate tools. Discover how to introduce true Database DevOps, brought to you in partnership with Redgate

Topics:
java ,nosql ,tips and tricks ,bottle ,flask

Published at DZone with permission of Ravi Hasija, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}