DEV Community

Cover image for Integrating MongoDB with Web Frameworks: Flask and Django
ajitdhulam for Python Discipline @EPAM India

Posted on

Integrating MongoDB with Web Frameworks: Flask and Django

Integrating MongoDB with Web Frameworks: Flask and Django:

1. Defining Models with Flask-MongoEngine:
Flask-MongoEngine simplifies integrating MongoDB with Flask applications. It provides an Object-Document Mapping (ODM) layer for MongoDB and Flask.

from flask import Flask
from flask_mongoengine import MongoEngine


app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
    'db': 'mydatabase',
    'host': 'localhost',
    'port': 27017
}
db = MongoEngine(app)


class User(db.Document):
    username = db.StringField(required=True, unique=True)
    email = db.EmailField(required=True)


# Create a new user
new_user = User(username="john_doe", email="john@example.com")
new_user.save()


# Query users
users = User.objects(username="john_doe")
Enter fullscreen mode Exit fullscreen mode

2. Integrating MongoDB with Django using Django-MongoDB-Engine:
Django-MongoDB-Engine allows Django to work with MongoDB as a database backend, providing a seamless integration experience.

from django.db import models
from djangotoolbox.fields import ListField, EmbeddedModelField
from mongodb_engine.fields import ObjectIdField


class User(models.Model):
    username = models.CharField(max_length=50, unique=True)
    email = models.EmailField()


# Create a new user
new_user = User(username="jane_doe", email="jane@example.com")
new_user.save()


# Query users
users = User.objects.filter(username="jane_doe")
Enter fullscreen mode Exit fullscreen mode

Note: Settings for this are different as you need to install some packages and modify settings, you can refer to the references section.

By integrating MongoDB with Flask and Django using their respective MongoDB extensions, you can seamlessly use MongoDB as a database backend for your web applications. This integration provides the flexibility of NoSQL databases while leveraging the features and convenience of popular web frameworks.

Top comments (0)