Flask & MongoDB - Material Kit (free sample)
Tags: webdev, flask, mongodb, opensource
Published: 2022-12-06 18:10:04

---
title: Flask & MongoDB - Material Kit (free sample)
published: true
description: Open-Source sample built with Flask and MongoDB on top of a modern Bootstrap 5 Design - Sources published on GitHub (MIT License).
tags: webdev, flask, mongodb, opensource
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1zxrhnvrlgeku5v4qlah.png
canonical_url: https://blog.appseed.us/flask-mongodb-material-kit/
---
Hello Coders! 

This article presents an open-source [Flask Sample that uses MongoDB](https://github.com/app-generator/sample-flask-mongo) for information persistence. MongoDB is a document database that simplifies classic database usage while still providing all the capabilities required by modern apps. Being released under the MIT License, the source code can be used for commercial projects or simply in eLearning activities.  

> Thank you! 

- 👉 [Flask MongoDB](https://github.com/app-generator/sample-flask-mongo) - `source code`
- 👉 [Flask Material Kit](https://flask-material-kit.appseed-srv1.com/) - `LIVE App`
- 🚀 Free [Support](https://appseed.us/support/) - via `Email` & `Discord`

![MongoDB & Flask - Open-Source Sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijpwvq26vvxydcn7vncx.png)

---

The [MongoDB](https://www.mongodb.com/what-is-mongodb) interface is provided by [Flask-MongoEngine](http://docs.mongoengine.org/projects/flask-mongoengine/en/latest/), a popular library that manages the connection using a simple object-oriented API. Here are the necessary steps to bind any Flask app to MongoDB.

> 👉 **Step #1** - Add MONGODB_SETTINGS in [configuration](https://github.com/app-generator/sample-flask-mongo/blob/master/apps/config.py)

This section is used by the Flask-MongoEngine library to connect and manage the read/write requests.  

```python
MONGODB_SETTINGS = {
        'PORT':27017,
        'host': os.getenv('MONGO_HOST','localhost'),
        'DB'  : os.getenv('MONGO_DB','materialkit-flask')
    }
```

The above code snippet loads the connection data from the environment but also can be used with hard-coded data as well.

---

>👉 **Step #2** - Create the Mongo "db" object and bind it to [Flask](https://github.com/app-generator/sample-flask-mongo/blob/master/apps/__init__.py)

```python
# ... (truncated content)

app = Flask(__name__)  # Create Flask object 
db  = MongoEngine()    # create the Mongo interface
db.init_app(app)       # bind MongoDB with Flask

# MongoDB sessions
app.session_interface = MongoEngineSessionInterface(db) 
```

--- 

> 👉 **Step #3** - Update [Models](https://github.com/app-generator/sample-flask-mongo/blob/master/apps/authentication/models.py) definition

```bash
from apps import db  # DB object is constructed in step #2

class Users(db.Document, UserMixin):

    meta = {'collection': 'users'}

    username = db.StringField(required=True)
    email    = db.EmailField(required=True)
    password = db.StringField(required=True)  
```

Two things are MongoDB-specific in this definition:

- `Users` reuse the definition of `db.document`
- `Object meta`: that specifies the `collection MongoDB` file

At this point, the app is fully configured to use Mongo persistence. Let's take a look at the sample code used by the [authentication layer](https://github.com/app-generator/sample-flask-mongo/blob/master/apps/authentication/routes.py) for user registration & sign-in.

--- 

> ✅ **Sign IN** Flow - Locate the current user

```python
# Import Model
from apps.authentication.models import Users

# Read Username value submitted by the user
username = request.form['username'] 

# Search the user (check if exists)
user = Users.objects(username=username).first() # <-- MongoDB Used HERE

if user:
  # here the user exists 
  # Check password (... content truncated)
  login_user(user)
else:
  # user not registered
```

We can see that the MongoDB query API is quite closer to the SqlAlchemy syntax, and even beginners or first-time users should accommodate fast.

---

> ✅ **Registration** Flow - Create new users (if not exists)

```bash
from apps.authentication.models import Users

# Read email submitted by the user
email = request.form['email']

# Check username already used
user = Users.objects(username=username).first() # <-- MongoDB Used HERE
if user:
  # username already taken 
  # return Error
  
# Check email already used
user = Users.objects(email=email).first() # <-- MongoDB Used HERE  
if user:
  # email already taken 
  # return Error

# All good here, let's create the user
user = Users(username=username,email=email,password=pass)
user.save() 
```

The application can be started in a local environment using the classic steps for any Flask project: install the dependencies, set up the environment, and start the project using Flask embedded server or other WSGI servers like Gunicorn or uWSGI.

Once the application is started, we should see the SignIN page (guest users are forced to authenticate). After the authentication, all private pages are accessible.

---

![Flask & MongoDB - SignIN Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wwx46x7gzy62xokda2r.png)

---

> **Flask & MongoDB** - Cover Image

![Flask & MongoDB - Cover Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z0cylq6ivcpc3nrm0k2d.png)

---

> **Flask & MongoDB** - Team Component

![Flask & MongoDB - Team Cards Component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qy3q9p0sudv7o2b09t5v.png)

---

This amazing design is provided for free by [Creative-Tim](https://www.creative-tim.com/product/material-kit?AFFILIATE=128200) with 60 frontend individual elements, like buttons, inputs, navbars, nav tabs, cards, alerts, and sample pages: user profile, contact page, sign-in, and landing page.

The design follows Google's Material Design patterns plus a unique component from the Creative-Tim design vision.

> The Bootstrap 5 version can be download from [this](https://www.creative-tim.com/product/material-kit?AFFILIATE=128200) location.

![Material Kit - Open-Source Bootstrap 5 Design](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y3acnz9u5l99cwqekk0r.png)

---

> `Thanks for reading!` For more resources and support, please access:

- 🚀 Free [support](https://appseed.us/support/) provided by AppSeed (email & Discord)
- 👉 More [free apps](https://appseed.us/apps/open-source/) crafted in Flask, Django, and [React](https://appseed.us/apps/react/)