python

How to Use MongoDB in Python Flask

Federico Trotta

Federico Trotta on

How to Use MongoDB in Python Flask

When developing software applications, data storage is a key concern. The reality is that your first concern should be the data model you choose, which in turn affects how you store data. Generally speaking, this means deciding between SQL and NoSQL databases.

In this article, you will learn how to use MongoDB, a popular NoSQL database, in a Flask application. First, you will learn why MongoDB is a good choice, and then we will implement a practical hands-on project using MongoDB in Flask.

Why Use MongoDB in a Python Flask Application?

MongoDB is an open-source document-oriented database management system (DBMS) classified as NoSQL, as it stores data in JSON-like documents (the so-called BSON).

MongoDB was designed with scalability and high availability in mind, making it suitable for large-scale web applications. It also provides automatic sharding capabilities, allowing users to distribute their data across multiple servers without having to worry about complex configurations or manual partitioning processes.

So, given its characteristics, here are some reasons why you might want to consider using MongoDB in your Flask applications:

  • Flexibility with data modeling: Unlike the classical relational databases, MongoDB allows you to define flexible schemas for your collections, given its NoSQL nature. This means that it allows you to work with unstructured and semi-structured data.
  • Scalability: MongoDB supports horizontal scaling through sharding, which enables distributing data across multiple servers while maintaining data consistency (all the shards form a sharded cluster, which acts as a single logical database). This allows you to handle increased loads to high degrees by increasing read/write throughput and storage capacity.
  • Easy integration: MongoDB integrates seamlessly with many programming languages and frameworks, including Python. In the case of Flask, for example, there are several libraries that make the integration process smooth, like pymongo, flask-pymongo, and Flask-MongoAlchemy.
  • Real-time applications: MongoDB provides the ability to manage real-time data streams efficiently by integrating seamlessly with other technologies such as Apache Kafka.

How to Use MongoDB in Flask: A Step-by-step Guide

Now that you know why you should use MongoDB with Flask, let's dive into a step-by-step tutorial on integrating it into your application. We'll implement basic CRUD operations for a "User" model.

Prerequisites

Before starting, ensure that you have installed the following:

  • Python version 3.x
  • pip package manager for Python
  • virtualenv module for creating isolated environments in Python projects
  • Any recent version of MongoDB

NOTE: As a prerequisite, you also need to create a new database named my_database in MongoDB: it will be used later in this tutorial. To do so:

  • Launch MongoDB (the command depends on your Operating System and version of MongoDB) after you have installed it.
  • Type use my_database to create a new database named my_database.
  • Insert data into a collection to make it usable. You can type something like: db.my_collection.insertOne({ name: "John Doe", age: 30 }).

Step 1: Define Project Structure

Supposing you call your main folder my_flask_mongo_app. Create the following structure:

plaintext
my_flask_mongo_app/ ├── app/ │ ├── __init__.py │ ├── models.py │ ├── routes.py │ └── config.py ├── venv/ └── run.py

NOTE: The venv directory will be created when you activate the virtual environment later.

Step 2: Create The Virtual Environment and Install the Needed Libraries

Now, create the virtual environment.

Linux/macOS::

Shell
python3 -m venv venv source venv/bin/activate

Windows:

Shell
python -m venv venv venv\Scripts\activate

Then install the needed libraries via pip:

Shell
pip install flask flask_pymongo

Step 3: Configure The Flask Application

In the app/ folder, compile the Python files as follows.

In config.py type:

Python
import os class Config: SECRET_KEY = os.urandom(24) MONGO_URI = "mongodb://localhost:27017/my_database"

This file defines the configuration for the Flask application. In particular:

  • MONGODB_URI specifies the database name, host, and port for connecting to MongoDB. In this case, you'll be using the local MongoDB server running on port 27017 and accessing my_database.
  • SECRET_KEY secures sessions and other security-related features in Flask.

In __init__.py write the following code:

Python
from flask import Flask from flask_pymongo import PyMongo from .config import Config # create PyMongo instance at module level mongo = PyMongo() def create_app(): app = Flask(__name__) app.config.from_object(Config) # Initialize mongo with the app mongo.init_app(app) from .routes import main app.register_blueprint(main) return app

This file initializes the Flask application by:

  • Creating a Flask instance and loading the configuration from Config.
  • Initializing PyMongo, which allows Flask to interact with MongoDB.
  • Importing and registering the main blueprint from routes.py, which contains the application's routes.

Step 4: Define MongoDB Models

In the models.py file, write the following:

Python
from . import mongo class User: @staticmethod def create(username, email): user = { 'username': username, 'email': email } mongo.db.users.insert_one(user) return user @staticmethod def get_by_username(username): return mongo.db.users.find_one({'username': username}) @staticmethod def update(username, new_email): mongo.db.users.update_one( {'username': username}, {'$set': {'email': new_email}} ) @staticmethod def delete(username): mongo.db.users.delete_one({'username': username})

This file defines the 'User' model with static methods for CRUD operations:

  • The create() method inserts a new user document into the collection of users.
  • The get_by_username() method retrieves a user document by username.
  • The update() method updates a user's email.
  • The delete() method deletes a user document by username.

Step 5: Implement Routes and CRUD Operations

Use the routes.py file to create the actual CRUD operations via routes in Flask:

Python
from flask import Blueprint, request, jsonify from .models import User main = Blueprint('main', __name__) @main.route('/users', methods=['POST']) def create_user(): data = request.json user = User.create(data['username'], data['email']) return jsonify(user), 201 @main.route('/users/<username>', methods=['GET']) def get_user(username): user = User.get_by_username(username) if user: return jsonify(user), 200 return jsonify({'error': 'User not found'}), 404 @main.route('/users/<username>', methods=['PUT']) def update_user(username): data = request.json User.update(username, data['email']) return jsonify({'message': 'User updated'}), 200 @main.route('/users/<username>', methods=['DELETE']) def delete_user(username): User.delete(username) return jsonify({'message': 'User deleted'}), 200

This code defines the API endpoints (routes) for the Flask application. In particular, each route corresponds to a CRUD operation:

  • POST /users: Creates a new user.
  • GET /users/<username>: Retrieves a user by username.
  • PUT /users/<username>: Updates a user's email.
  • DELETE /users/<username>: Deletes a user.

Step 7: Create and Run the Main Application File

To create the main application, write the following code into the run.py file:

Python
from app import create_app app = create_app() if __name__ == '__main__': app.run(debug=True)

This file creates the Flask app and MongoDB connection using the create_app() function from app/__init__.py.

Then, run the application by typing:

Shell
python3 run.py

While the application runs, you can test the API endpoints using tools like Postman or curl.

For example, to create a new user, send a POST request to http://localhost:5000/users with the following JSON payload:

JSON
{ "username": "john_doe", "email": "johndoe@example.com" }

You can do it via curl like so:

Shell
curl -X POST \ -H "Content-Type: application/json" \ -d '{"username": "john_doe", "email": "john@example.com"}' \ http://localhost:5000/users

That's all! Now you know the basics of how to use MongoDB in Flask.

Wrapping Up

In this article, we learned how to use MongoDB in Flask. First, we explored why and when you should use MongoDB. Then, we offered a step-by-step guide on using MongoDB in Flask that supports and implements basic CRUD operations for a "User" model.

Oh, and by the way, did you know that AppSignal provides MongoDB and Flask integrations? Give them a try for a superior monitoring experience with AppSignal!

Happy coding!

Wondering what you can do next?

Finished this article? Here are a few more things you can do:

  • Share this article on social media
Federico Trotta

Federico Trotta

Guest author Federico is a freelance Technical Writer who specializes in writing technical articles and documenting digital products. His mission is to democratize software through technical content.

All articles by Federico Trotta

Become our next author!

Find out more

AppSignal monitors your apps

AppSignal provides insights for Ruby, Rails, Elixir, Phoenix, Node.js, Express and many other frameworks and libraries. We are located in beautiful Amsterdam. We love stroopwafels. If you do too, let us know. We might send you some!

Discover AppSignal
AppSignal monitors your apps