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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How to Upload/Download a File To and From the Server
  • Beyond Django and Flask: How FastAPI Became Python's Fastest-Growing Framework for Production APIs
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)

Trending

  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • PWA on iOS, Part 2: HTTPS, Manifest and Service Worker
  • Designing Frontend Applications for Failure, Not Just Success
  • Evals in CI: How to Catch Agent Regressions Before Production Does

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jan. 14, 15 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. 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
  • Beyond Django and Flask: How FastAPI Became Python's Fastest-Growing Framework for Production APIs
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook