MongoDB

Integrating MongoDB with Flask involves using a MongoDB database to store and manage data within your Flask application. Unlike relational databases, MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Here’s a step-by-step guide to integrating MongoDB with Flask using Flask-PyMongo, which is a Flask extension that simplifies using PyMongo (MongoDB Python driver) with Flask.

Steps for Integrating MongoDB with Flask

  1. Install Necessary Packages:
    • You need to install flask-pymongo for MongoDB integration.
    pip install flask-pymongo
    
  2. Configure MongoDB Connection:
    • Update the config.py file to specify the MongoDB connection URI.
    # config.py
    import os
    
    class Config:
        SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
        MONGO_URI = os.environ.get('MONGO_URI') or 'mongodb://localhost:27017/mydatabase'
    
    • Replace mongodb://localhost:27017/mydatabase with your MongoDB URI. This includes the database name (mydatabase in this example) and the MongoDB server's URI.
  3. Initialize Flask-PyMongo:
    • Set up Flask-PyMongo in your app/__init__.py file.
    from flask import Flask
    from flask_pymongo import PyMongo
    
    mongo = PyMongo()
    
    def create_app():
        app = Flask(__name__)
        app.config.from_object('config.Config')
    
        mongo.init_app(app)
    
        from .routes import bp as main_bp
        app.register_blueprint(main_bp)
    
        return app
    
  4. Database Operations:
    • Perform MongoDB operations within your Flask routes using Flask-PyMongo.
    # app/routes.py
    from flask import Blueprint, render_template, request, redirect, url_for
    from . import mongo
    
    bp = Blueprint('main', __name__)
    
    @bp.route('/')
    def index():
        users = mongo.db.users.find()
        return render_template('index.html', users=users)
    
    @bp.route('/add_user', methods=['POST'])
    def add_user():
        username = request.form['username']
        email = request.form['email']
        mongo.db.users.insert_one({'username': username, 'email': email})
        return redirect(url_for('main.index'))
    
  5. Access MongoDB Collections:
    • Use mongo.db.collection_name to access MongoDB collections (users in this example).
    • Perform CRUD operations using PyMongo methods like find(), insert_one(), update_one(), delete_one(), etc.

Example Project Structure

Project Structure:

my_flask_project/
├── app/
│   ├── __init__.py
│   ├── routes.py
│   ├── templates/
│   │   └── index.html
│   └── static/
│       ├── css/
│       │   └── style.css
│       ├── js/
│       │   └── script.js
│       └── images/
│           └── logo.png
├── run.py
└── config.py

app/routes.py:

from flask import Blueprint, render_template, request, redirect, url_for
from . import mongo

bp = Blueprint('main', __name__)

@bp.route('/')
def index():
    users = mongo.db.users.find()
    return render_template('index.html', users=users)

@bp.route('/add_user', methods=['POST'])
def add_user():
    username = request.form['username']
    email = request.form['email']
    mongo.db.users.insert_one({'username': username, 'email': email})
    return redirect(url_for('main.index'))

run.py:

from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

config.py:

import os

class Config:
    SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
    MONGO_URI = os.environ.get('MONGO_URI') or 'mongodb://localhost:27017/mydatabase'

app/init.py:

from flask import Flask
from flask_pymongo import PyMongo

mongo = PyMongo()

def create_app():
    app = Flask(__name__)
    app.config.from_object('config.Config')

    mongo.init_app(app)

    from .routes import bp as main_bp
    app.register_blueprint(main_bp)

    return app

app/templates/index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User List</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>User List</h1>
    <ul>
        {% for user in users %}
        <li>{{ user.username }} - {{ user.email }}</li>
        {% endfor %}
    </ul>
    <h2>Add User</h2>
    <form action="{{ url_for('main.add_user') }}" method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br>
        <button type="submit">Add User</button>
    </form>
</body>
</html>

Summary

  1. Flask-PyMongo: Provides integration between Flask and MongoDB.
  2. Configuration: Set up your MongoDB URI and other configurations in config.py.
  3. Initialization: Initialize Flask-PyMongo in your Flask application setup (app/__init__.py).
  4. Operations: Perform CRUD operations using PyMongo methods (insert_one(), find(), etc.) within Flask routes.
  5. Project Structure: Maintain a well-organized project structure for scalability and maintainability.

By following these steps, you can effectively integrate MongoDB into your Flask applications, leveraging its flexibility and scalability for storing and managing data.