Flask is a micro - framework, meaning it provides only the essential components for building web applications, such as routing, request handling, and template rendering. It gives developers the freedom to choose the components they need, like database integration or form validation libraries.
MongoDB is a NoSQL database that uses a document - based data model. Instead of tables and rows like in relational databases, MongoDB stores data in documents (similar to JSON objects). These documents are organized into collections, which are analogous to tables in a relational database.
Flask can interact with MongoDB using a Python driver called pymongo
. This driver allows Flask applications to connect to a MongoDB instance, perform CRUD (Create, Read, Update, Delete) operations, and handle data retrieved from the database.
Before you can start using Flask with MongoDB, you need to set up your development environment. Here are the steps:
pip
, the Python package manager.pip install flask
pymongo
:
pymongo
is the official MongoDB driver for Python. Install it using pip
.pip install pymongo
sudo systemctl start mongod
Flask with MongoDB can be used to build a simple CMS. The unstructured nature of MongoDB allows for easy storage of different types of content, such as articles, images, and videos. Flask can handle the user interface and routing, while MongoDB stores the content.
In an e - commerce application, MongoDB can store product information, customer profiles, and order details. Flask can be used to build the front - end and handle user requests, such as product searches and checkout processes.
Flask can serve as the web server for a real - time analytics dashboard. MongoDB can store the data generated by various sources, and Flask can query this data and present it in a visual format on the dashboard.
from flask import Flask
from pymongo import MongoClient
app = Flask(__name__)
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
# Select a database
db = client['my_database']
# Select a collection
collection = db['my_collection']
@app.route('/')
def index():
return 'Connected to MongoDB!'
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']
collection = db['my_collection']
@app.route('/insert')
def insert_document():
data = {'name': 'John Doe', 'age': 30}
result = collection.insert_one(data)
return f'Document inserted with ID: {result.inserted_id}'
if __name__ == '__main__':
app.run(debug=True)
from flask import Flask, jsonify
from pymongo import MongoClient
app = Flask(__name__)
client = MongoClient('mongodb://localhost:27017/')
db = client['my_database']
collection = db['my_collection']
@app.route('/get_documents')
def get_documents():
documents = list(collection.find())
for doc in documents:
doc['_id'] = str(doc['_id']) # Convert ObjectId to string for JSON serialization
return jsonify(documents)
if __name__ == '__main__':
app.run(debug=True)
MongoDB uses ObjectId
as the default primary key for documents. When retrieving documents and trying to serialize them to JSON (for example, when returning them from a Flask route), ObjectId
is not JSON - serializable. You need to convert it to a string manually, as shown in the code example above.
If the MongoDB server is down or there is a network issue, the application will raise an exception. It’s important to add proper error handling in your Flask application to handle these situations gracefully.
Not properly sanitizing user input can lead to security vulnerabilities, such as NoSQL injection attacks. Always validate and sanitize user input before using it in MongoDB queries.
Store sensitive information, such as the MongoDB connection string, in environment variables. This makes it easier to manage different configurations for development, testing, and production environments.
import os
from flask import Flask
from pymongo import MongoClient
app = Flask(__name__)
# Get the connection string from environment variable
mongo_uri = os.getenv('MONGO_URI', 'mongodb://localhost:27017/')
client = MongoClient(mongo_uri)
Proper indexing in MongoDB can significantly improve query performance. Identify the fields that are frequently used in queries and create indexes on them.
Write unit and integration tests for your Flask application. Use testing frameworks like pytest
to test the database operations and the Flask routes.
Using Flask with MongoDB is a powerful combination for building dynamic web applications. Flask’s simplicity and flexibility, combined with MongoDB’s ability to handle unstructured data, make it suitable for a wide range of use cases. By understanding the core concepts, being aware of common pitfalls, and following best practices, you can effectively develop and deploy real - world applications using these technologies.
pymongo
Documentation:
https://pymongo.readthedocs.io/