Back
Featured image of post Integrating Flask With Mongodb

Integrating Flask With Mongodb

hello and welcome to my another post this time I will discuss how Flask integration with Mongo DB, now Before starting we have to know what to be prepared first, like

  • Installing Mongo DB on Your Server
  • Install MongoDB Management Tools

In this time we only dicuss about Integrating Flask with Mongo DB, in this case we create simple project named flaskr-mongo it is a simple Blog API project that applies flask and Mongo DB

Project Concept

in This Project, we will create a project blog, that includes

  • title
  • post content

the structure of the project will be like this

├── Makefile
├── manage.py
├── projects
│   ├── blog
│   │   ├── api
│   │   │   ├── __init__.py
│   │   │   ├── routes.py
│   │   │   └── views.py
│   │   ├── __init__.py
│   │   └── models.py
│   ├── config.py
│   └── __init__.py
├── README.md
└── requirements.txt

Creating Project

in this section we will creating Project following this structure

.
├── manage.py
└── projects
└── __init__.py

before we code we must selecting package for mongo connector first, below is available package and ready to use for integrate flask and mongo DB

free to use whichever one, but in this post, I will use MongoEngine

Installing Library

install library with pip

pip install flask flask-restful flask-mongoengine

Create Base Project Structure

after install create a package named projects and initialize your flask application


# projects/__init__.py
import os

from flask import Flask
from flask_mongoengine import MongoEngine

from projects.blog.api.routes import blog_api_blueprint

db = MongoEngine()


def create_app():
    app = Flask(__name__, static_url_path='')

    # set config
    app_settings = os.getenv('APP_SETTINGS')
    app.config.from_object(app_settings)

    # setup extension
    db.init_app(app)

    app.register_blueprint(blueprint=blog_api_blueprint)

    # shell context for flask cli
    @app.shell_context_processor
    def ctx():
        return {'app': app, 'db': db}

    return app

Creating Models

now let’s create a model for mapping data

# projects/blog/models.py
import mongoengine as me
from datetime import datetime

class Posts(me.Document):
    title: str = me.StringField(required=True, max_length=200)
    contents: str = me.StringField(required=True)
    created_on = me.DateTimeField(default=datetime.now())

after creating models, the next step is to create a database for our application, in this case, I using Mongo DB compass to manage my mongo database, you can download it here

Creating Database

The next step after downloading is creating a database, to create the database you need to open your mongo compass and create database

Create Database
Create Database

the Collection name is the same as your models in your models.py, in my case my models named Posts

Configure Applications

the next step is creating a config file for your application to set up your application integrates with mongo database or many other, create file config named config.py inside projects directory

import os

class BaseConfig:
    TESTING: bool = False
    SECRET_KEY: str = '@Flaskr-MongoSeCretKeyS'
    DEBUG: bool = False


class DevelopmentConfig(BaseConfig):
    MONGODB_SETTINGS: dict = {
        'db': 'flask_blog_db',
        'host': 'localhost',
        'port': 27017
    }
    BASE_DIR = os.path.abspath(os.path.dirname(__file__))


class ProductionConfig(BaseConfig):
    pass

in config.py we create database connection config and many other configs on there, now let’s set up to automate running for our Application using Makefile

because I run this project on Linux you can set it up like this

run-dev:
	export FLASK_APP=manage.py && export FLASK_ENV=development && export APP_SETTINGS='projects.config.DevelopmentConfig' && flask run

now you can run in a terminal using this command

make run-dev

run flask using makefile
run flask using makefile

Creating Views to Implement CRUD Operation

now in this step, we will create a view to implementing CRUD (Create, Read, Update, Delete) Operations for our Application

from flask_restful import abort, fields, marshal_with, Resource, reqparse
from flask import jsonify
from projects.blog.models import Posts

# reqparse
posts_parser = reqparse.RequestParser()
posts_parser.add_argument('title', type=str, help="Title is Required", required=True)
posts_parser.add_argument('contents', type=str, help='Contents is Required', required=True)

posts_update = reqparse.RequestParser()
posts_update.add_argument('title', type=str)
posts_update.add_argument('contents', type=str)

# resource fields
resource_fields = {
    'id': fields.String,
    'title': fields.String,
    'contents': fields.String
}


# views
class PostListView(Resource):
    def get(self):
        posts = Posts.objects()
        return jsonify(posts)

    @marshal_with(resource_fields)
    def post(self):
        args = posts_parser.parse_args()
        posts = Posts(title=args['title'], contents=args['contents'])
        posts.save()
        return jsonify({'Messages': 'Data Posted Successfullly'}), 201


class PostDetailView(Resource):

    @marshal_with(resource_fields)
    def get(self, post_id: str):
        post = Posts.objects.get(id=post_id)
        if not post:
            abort(404, message=f"Post with id: {post_id} not found")
        return post

    @marshal_with(resource_fields)
    def put(self, post_id: str):
        args = posts_update.parse_args()
        if args['title']:
            Posts.objects.get(id=post_id).update(title=args['title'])
        if args['contents']:
            Posts.objects.get(id=post_id).update(title=args['contents'])
        return jsonify(Posts.objects.get(_id=post_id).first()), 200

    def delete(self, post_id: str):
        posts = Posts.objects(id=post_id)
        posts.delete()
        return jsonify({"message": f"Post with id {post_id} Deleted"}), 204

Defining Route for Our Blog API Projects

in the last step, we define a route for our views, which we just created in the previous step

from flask import Blueprint
from flask_restful import Api

# API Blueprint
from projects.blog.api.views import PostListView, PostDetailView

blog_api_blueprint = Blueprint('blog', __name__, template_folder='templates', static_folder='static')
blog_api = Api(blog_api_blueprint)

# routes
blog_api.add_resource(PostListView, "/blog/api/posts/")
blog_api.add_resource(PostDetailView, "/blog/api/posts/<post_id>/")

Test Our Application

now our application, in this case, I use Postman

Get Blog List
Get Blog List

Get Spesific Data
Get Spesific Data

Conclusion

with Mongo DB we can process data more easily just like we process JSON files or dictionaries and lists in python, thank you for reading, hopefully, it’s useful, click here to join our community, source code available on Github

Licensed under CC BY-NC-SA 4.0
Last updated on Jan 13, 2022 18:08 +0700
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy