5. Flask PyMongo

Flask-PyMongo is an extension for Flask that simplifies working with MongoDB, a NoSQL database, within a Flask application. It provides an easy way to integrate MongoDB into Flask and manage database operations using PyMongo.

Installation

First, you need to install Flask and Flask-PyMongo. You can do this using pip:

pip install Flask Flask-PyMongo

Basic Usage

Here's a basic example of how to use Flask-PyMongo:

  1. Set up the Flask app and configure the MongoDB connection:

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

app = Flask(__name__)

# Replace the URI string with your MongoDB connection string
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"

mongo = PyMongo(app)
  1. Define a route to interact with the database:

@app.route('/add', methods=['POST'])
def add_user():
    # Get the JSON data from the request
    data = request.get_json()
    
    # Insert the data into the "users" collection
    mongo.db.users.insert_one(data)
    
    return jsonify(message="User added successfully"), 201

@app.route('/users', methods=['GET'])
def get_users():
    # Retrieve all users from the "users" collection
    users = mongo.db.users.find()
    
    # Convert the MongoDB documents to a list of dictionaries
    result = []
    for user in users:
        user['_id'] = str(user['_id'])  # Convert ObjectId to string
        result.append(user)
    
    return jsonify(result), 200
  1. Run the Flask app:

Explanation

  • Configuration (app.config["MONGO_URI"]): This line sets the MongoDB URI. The URI specifies the location of the MongoDB server and the database to use.

  • PyMongo instance (mongo = PyMongo(app)): This line creates a PyMongo instance, linking it to the Flask app.

  • Route /add: This route handles POST requests to add a new user to the "users" collection in the database. The data is received in JSON format and inserted into the collection.

  • Route /users: This route handles GET requests to retrieve all users from the "users" collection. It converts the MongoDB documents to a list of dictionaries, converting the ObjectId to a string for JSON compatibility.

Running the Application

  1. Start your MongoDB server. If you're running it locally, you can typically start it with the command:

  1. Run your Flask application:

  1. Use a tool like Postman or curl to interact with the endpoints:

  • To add a user:

  • To get all users:

This is a simple example to get you started with Flask-PyMongo. You can build upon this by adding more complex operations and handling various types of MongoDB queries.

Last updated