Registry / web-framework / flask-pymongo

flask-pymongo

JSON →
library3.0.1pypypi✓ verified 86d ago

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.

pip install Flask-PyMongo
INSTALL
IMPORT
SIG · FLASK-PYMONGO
F
flask-pymongo
web-frameworkpythonv3.0.1
Install
3.2s avg
Import
709ms
Disk
31MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.0.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.741s · 30.5MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 3.2s · import 0.676s · 33MB
31MB installed
● package 31MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

PyMongo
from flask_pymongo import PyMongo
from flask.ext.pymongo import PyMongo
The `flask.ext` import path was deprecated and removed in Flask-PyMongo 2.0. Use direct import from `flask_pymongo`.

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)
Debug
Known issues
breakingFlask-PyMongo 2.0 introduced breaking changes, most notably deprecating individual configuration variables (e.g., `MONGO_HOST`, `MONGO_PORT`, `MONGO_DBNAME`) in favor of a single `MONGO_URI`.
fix
Migrate your application's MongoDB configuration to use the `MONGO_URI` format (e.g., `mongodb://localhost:27017/myDatabase`). Pin `Flask-PyMongo<2.0` if immediate migration is not possible.
affects: <2.0 to >=2.0
breakingVersion 3.x of Flask-PyMongo requires Flask 3.0+ and PyMongo 4.0+ and Python 3.9+. Older versions of Flask or PyMongo are not supported.
fix
Ensure your project's Flask version is 3.0 or higher, PyMongo is 4.0 or higher, and Python is 3.9 or higher. Adjust your `requirements.txt` accordingly.
affects: All versions
gotchaBy default, Flask-PyMongo sets `connect=False` during initialization to prevent PyMongo from connecting immediately, which avoids fork-safety issues. If you need immediate connection, explicitly pass `connect=True`.
fix
If you require PyMongo to connect immediately upon instantiation, initialize it with `mongo = PyMongo(app, connect=True)`. Otherwise, be aware that the actual connection might be delayed until the first database operation.
affects: All versions
gotchaAs of Flask-PyMongo 2.2, if the `MONGO_URI` does not specify a database name, the `mongo.db` attribute will be `None`. Attempting to access `mongo.db.<collection>` will result in an AttributeError.
fix
Always include a database name in your `MONGO_URI` (e.g., `mongodb://localhost:27017/myDatabase`) if you intend to use `mongo.db` directly. Alternatively, access collections via `mongo.cx.<database_name>.<collection_name>`.
affects: >=2.2
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'flask_pymongo'
Flask-PyMongo is either not installed or installed in a different Python environment (e.g., for Python 2 while running Python 3, or in an inactive virtual environment).
fix
Ensure you have installed `Flask-PyMongo` within your active Python environment. Use `pip install Flask-PyMongo` (or `pip3 install Flask-PyMongo`) and verify with `python -c 'import flask_pymongo'` in the same environment.
pymongo.errors.ServerSelectionTimeoutError: <hostname>:<port>: [Errno 111] Connection refused, Timeout: 30s
The MongoDB server is not running, is inaccessible from the application's host, or the connection URI is incorrect. This can be due to an incorrect host/port, firewall rules, or the MongoDB service not being started.
fix
Verify that your MongoDB server is running and accessible from where your Flask application is hosted. Check the `MONGO_URI` for correct host, port, and credentials. Ensure no firewall is blocking the connection. Restarting the MongoDB service often resolves this.
pymongo.errors.OperationFailure: Authentication failed.
Incorrect username or password in the `MONGO_URI`, or the specified user does not have access to the database. For older MongoDB versions, it could also mean the database name was omitted from the URI while using credentials.
fix
Double-check your MongoDB username, password, and database name in the `MONGO_URI`. Ensure the user has the necessary permissions. For older MongoDB versions, explicitly include the database name in the URI even if authenticating against `admin`.
Upgrade
Version history
3.0.1latest on PyPI · released Jan 29, 2025
Audit
Dependencies
FlaskrequiredWeb framework integration
PyMongorequiredMongoDB driver
Agent activity
6 hits · last 30 days
node
4
Resources
flask-pymongo — pip install flask-pymongo · libregistry