DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Upload/Download a File To and From the Server
  • Enable Faster Uploads and Downloads with Your S3 Bucket
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Build a Data Analytics Platform With Flask, SQL, and Redis

Trending

  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • The Role of AI in Identity and Access Management for Organizations
  • Integrating Model Context Protocol (MCP) With Microsoft Copilot Studio AI Agents
  • The End of “Good Enough Agile”
  1. DZone
  2. Coding
  3. Frameworks
  4. Upload and Download File From Mongo Using Bottle and Flask

Upload and Download File From Mongo Using Bottle and Flask

By 
Ravi Isnab user avatar
Ravi Isnab
·
Jan. 14, 15 · Interview
Likes (1)
Comment
Save
Tweet
Share
13.8K Views

Join the DZone community and get the full member experience.

Join For Free

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:

  1. MongoDB: http://www.mongodb.org/↩
  2. GridFS: http://docs.mongodb.org/manual/core/gridfs/↩
  3. Bottle: http://bottlepy.org/docs/dev/tutorial.html↩
  4. Flask: http://flask.pocoo.org/↩
  5. PyMongo GridFS doc http://api.mongodb.org/python/current/api/gridfs/index.html?highlight=gridfs#module-gridfs↩
  6. Get to know GridFS: https://dzone.com/articles/get-know-gridfs-mongodb↩
Bottle (web framework) Flask (web framework) Upload Download

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

Opinions expressed by DZone contributors are their own.

Related

  • How to Upload/Download a File To and From the Server
  • Enable Faster Uploads and Downloads with Your S3 Bucket
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • Build a Data Analytics Platform With Flask, SQL, and Redis

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!