MongoDB is an open source database that stores flexible JSON-like “documents,” which can have any number, name, or hierarchy of fields within, instead of rows of data as in a relational database. Python developers can think of MongoDB as a persistent, searchable repository of Python dictionaries (and, in fact, this is how PyMongo represents MongoDB documents).
Flask-PyMongo bridges Flask and PyMongo, so that you can use Flask’s normal mechanisms to configure and connect to MongoDB.
First, install Flask-PyMongo:
$ pip install Flask-PyMongo
Flask-PyMongo depends, and will install for you, recent versions of Flask (0.8 or later) and PyMongo (2.4 or later).
Next, add a PyMongo to your code:
from flask import Flask
from flask.ext.pymongo import PyMongo
app = Flask(__name__)
mongo = PyMongo(app)
PyMongo connects to the MongoDB server running on port 27017 on localhost, and assumes a default database name of app.name (i.e. whatever name you pass to Flask). This database is exposed as the db attribute.
You can use db directly in views:
@app.route('/')
def home_page():
online_users = mongo.db.users.find({'online': True})
return render_template('index.html',
online_users=online_users)
Flask-PyMongo provides helpers for some common tasks:
Find and return a single document, or raise a 404 Not Found exception if no document matches the query spec. See find_one() for details.
@app.route('/user/<username>')
def user_profile(username):
user = mongo.db.users.find_one_or_404({'_id': username})
return render_template('user.html',
user=user)
Return an instance of the response_class containing the named file, and implement conditional GET semantics (using make_conditional()).
@app.route('/uploads/<path:filename>')
def get_upload(filename):
return mongo.send_file(filename)
| Parameters: |
|
|---|
Save the file-like object to GridFS using the given filename. Returns None.
@app.route('/uploads/<path:filename>', methods=['POST'])
def save_upload(filename):
mongo.save_file(filename, request.files['file'])
return redirect(url_for('get_upload', filename=filename))
| Parameters: |
|
|---|
A simple converter for the RESTful URL routing system of Flask.
@app.route('/<ObjectId:task_id>')
def show_task(task_id):
task = mongo.db.tasks.find_one_or_404(task_id)
return render_template('task.html', task=task)
It checks the validate of the id and converts it into a ObjectId object. The converter will be automatically registered by the initialization of PyMongo with keyword ObjectId.
PyMongo understands the following configuration directives:
| MONGO_URI | A MongoDB URI which is used in preference of the other configuration variables. |
| MONGO_HOST | The host name or IP address of your MongoDB server. Default: “localhost”. |
| MONGO_PORT | The port number of your MongoDB server. Default: 27017. |
| MONGO_AUTO_START_REQUEST | Set to False to disable PyMongo 2.2’s “auto start request” behavior (see MongoClient). Default: True. |
| MONGO_MAX_POOL_SIZE | (optional): The maximum number of idle connections maintained in the PyMongo connection pool. Default: PyMongo default. |
| MONGO_DBNAME | The database name to make available as the db attribute. Default: app.name. |
| MONGO_USERNAME | The user name for authentication. Default: None |
| MONGO_PASSWORD | The password for authentication. Default: None |
| MONGO_REPLICA_SET | The name of a replica set to connect to; this must match the internal name of the replica set (as deteremined by the isMaster command). Default: None. |
| MONGO_READ_PREFERENCE | Determines how read queries are routed to the replica set members. Must be one of PRIMARY, SECONDARY, or SECONDARY_ONLY, or the string names thereof. Default PRIMARY. |
| MONGO_DOCUMENT_CLASS | This tells pymongo to return custom objects instead of dicts, for example bson.son.SON. Default: dict |
When PyMongo or init_app() are invoked with only one argument (the Flask instance), a configuration value prefix of MONGO is assumed; this can be overridden with the config_prefix argument.
This technique can be used to connect to multiple databases or database servers:
app = Flask(__name__)
# connect to MongoDB with the defaults
mongo1 = PyMongo(app)
# connect to another MongoDB database on the same host
app.config['MONGO2_DBNAME'] = 'dbname_two'
mongo2 = PyMongo(app, config_prefix='MONGO2')
# connect to another MongoDB server altogether
app.config['MONGO3_HOST'] = 'another.host.example.com'
app.config['MONGO3_PORT'] = 27017
app.config['MONGO3_DBNAME'] = 'dbname_three'
mongo3 = PyMongo(app, config_prefix='MONGO3')
Some auto-configured settings that you should be aware of are:
Ascending sort order.
Descending sort order.
Send all queries to the replica set primary, and fail if none exists.
Distribute queries among replica set secondaries unless none exist or are up, in which case send queries to the primary.
Distribute queries among replica set secondaries, and fail if none exist.
Automatically connects to MongoDB using parameters defined in Flask configuration.
The automatically created Connection or ReplicaSetConnection object.
The automatically created Database object corresponding to the provided MONGO_DBNAME configuration parameter.
Initialize the app for use with this PyMongo. This is called automatically if app is passed to __init__().
The app is configured according to the configuration variables PREFIX_HOST, PREFIX_PORT, PREFIX_DBNAME, PREFIX_AUTO_START_REQUEST, PREFIX_REPLICA_SET, PREFIX_READ_PREFERENCE, PREFIX_USERNAME, PREFIX_PASSWORD, and PREFIX_URI where “PREFIX” defaults to “MONGO”. If PREFIX_URL is set, it is assumed to have all appropriate configurations, and the other keys are overwritten using their values as present in the URI.
| Parameters: |
|
|---|
Save the file-like object to GridFS using the given filename. Returns None.
@app.route('/uploads/<path:filename>', methods=['POST'])
def save_upload(filename):
mongo.save_file(filename, request.files['file'])
return redirect(url_for('get_upload', filename=filename))
| Parameters: |
|
|---|
Return an instance of the response_class containing the named file, and implement conditional GET semantics (using make_conditional()).
@app.route('/uploads/<path:filename>')
def get_upload(filename):
return mongo.send_file(filename)
| Parameters: |
|
|---|
Custom sub-class of pymongo.collection.Collection which adds Flask-specific helper methods.
Find and return a single document, or raise a 404 Not Found exception if no document matches the query spec. See find_one() for details.
@app.route('/user/<username>')
def user_profile(username):
user = mongo.db.users.find_one_or_404({'_id': username})
return render_template('user.html',
user=user)
These classes exist solely in order to make expressions such as mongo.db.foo.bar evaluate to a Collection instance instead of a pymongo.collection.Collection instance. They are documented here solely for completeness.
Returns instances of flask_pymongo.wrappers.Database instead of pymongo.database.Database when accessed with dot notation.
Returns instances of flask_pymongo.wrappers.Database instead of pymongo.database.Database when accessed with dot notation.
Returns instances of flask_pymongo.wrappers.Collection instead of pymongo.collection.Collection when accessed with dot notation.
Changes:
Contributors: