Flask-PyMongo
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
-
ModuleNotFoundError: No module named 'flask_pymongo'
cause 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).fixEnsure 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
cause 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.fixVerify 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.
cause 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.fixDouble-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`.
Warnings
- breaking Flask-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`.
- breaking Version 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.
- gotcha By 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`.
- gotcha As 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.
Install
-
pip install Flask-PyMongo
Imports
- PyMongo
from flask.ext.pymongo import PyMongo
from flask_pymongo import PyMongo
Quickstart
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)