Flask-PyMongo

3.0.1 · active · verified Thu Apr 16

Flask-PyMongo is a Python library that provides PyMongo support for Flask applications. It acts as a bridge between Flask and PyMongo, wrapping PyMongo's MongoClient, Database, and Collection classes to offer convenience helpers and seamless integration with Flask's configuration system. The current version, 3.0.1, is actively maintained and generally follows the release cycles of Flask and PyMongo.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes a Flask application and connects it to a MongoDB instance using Flask-PyMongo. The MongoDB URI is configured via `app.config['MONGO_URI']`, which can be set through an environment variable. A simple route demonstrates checking the database connection.

from flask import Flask, jsonify
from flask_pymongo import PyMongo
import os

app = Flask(__name__)

# Configure MongoDB URI from environment variable or default
app.config["MONGO_URI"] = os.environ.get("MONGO_URI", "mongodb://localhost:27017/myDatabase")

mongo = PyMongo(app)

@app.route("/")
def home_page():
    try:
        # Ensure connection is established before querying
        mongo.cx.admin.command('ping')
        return jsonify(message="MongoDB connection successful!")
    except Exception as e:
        return jsonify(message=f"MongoDB connection failed: {e}"), 500

if __name__ == "__main__":
    # In a real application, you might use a more robust run method or WSGI server
    app.run(debug=True)

view raw JSON →