How to Use MongoDB in Python Flask

4 months ago 8

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:

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::

Windows:

Then install the needed libraries via pip:

Step 3: Configure The Flask Application

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

In config.py type:

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:

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:

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:

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:

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

Then, run the application by typing:

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:

You can do it via curl like so:

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!

Read Entire Article