Create Python Flask App in MVC Format

Flask is a micro framework written in Python. It helps to create small app to large scale web application.

Advantages of using flask framework is as follows:

  1. Easy installation

  2. Small size

  3. Large community support

  4. Fast in execution


In this article we will create a simple blog to understand the structure and code pattern of flask framework.


Create flask project

You may already installed python. If not installed please follow the link below.


Install PIP that is a package installer in python.

curl "" -o ""


Install environment for flask app.

pip install Flask

pip install virtualenv

Now create your application directory on your desired location. In our example this is flaskblog.


Clone Flask MVC  Structure from Github:

git clone


You will get the file structure as follows:



      L app

L controller



L helpers



L models



L routes




L static

L views





Now start Flask App:

sudo pip install -e .

export FLASK_APP=app/

export FLASK_DEBUG=1

flask run


You will get the following message:


* Serving Flask app "app"

* Forcing debug mode on

* Running on (Press CTRL+C to quit)

* Restarting with stat

* Debugger is active!

* Debugger PIN: 114-170-438


Now open browser and open link:


To change database connection open app/ and configure

config['MONGO_DBNAME'] = 'flaskblog'

config['MONGO_URI'] = 'mongodb://localhost:27017/flaskblog'

Now create a post model to retrieve posts. Create a file in models directory.

Write the code inside that:

from import mongo

from flask_pymongo import ObjectId

from app.helpers.Utility import toDictionaryArray

from datetime import datetime

class PostModel():

  def __init__(self):


  def getPost(self,_id):

      users = mongo.db.posts.find({'_id':ObjectId(_id)})


      return post[0]

  def getAllPosts(self):

      users = mongo.db.posts.find()

      return toDictionaryArray(users)

  def addPost(self, title, content,image):

      d =

      insertdata = {'title': title, 'content': content, 'image': image, 'status': "1", 'created_at': d, 'updated_at': d}

      res = mongo.db.posts.insert(insertdata)

      return str(ObjectId(res))

  def updatePost(self, _id,title, content,image):

      d =

      updatedata = {'title': title, 'content': content, 'image': image, 'status': "1", 'updated_at': d}

      mongo.db.posts.update({'_id': ObjectId(_id)}, {'$set': updatedata}, False, True)

      return _id

  def deletePost(self, _id):

      mongo.db.posts.delete_many({'_id': ObjectId(_id)})



Add in helpers/

def allowed_file(filename, ALLOWED_EXTENSIONS):

  return '.' in filename and \

         filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


Update Home Controller:

from flask import request,redirect

from flask import render_template

from app.models.AuthModel import authmodel

from app.models.PostModel import postmodel

from app.helpers.Utility import sendResponse,allowed_file

import os

import time

class HomeController():

  def __init__(self):


  def index(self):


      return render_template('index.html', title='Home', posts=posts)

  def register(self):

      return render_template('registration.html', title='Registration')

  def new(self):

      return render_template('createpost.html', title='New Post')

  def registeruser(self):

      _firstname = request.form.get('firstname', '')

      _lastname = request.form.get('lastname', '')

      _email = request.form.get('email', '')

      _password = request.form.get('password', '')

      return sendResponse(authmodel.registerUser(_firstname,_lastname,_email,_password))

  def writePost(self):



      image = request.files['image']


      if image and allowed_file(image.filename, set(['png', 'jpg', 'jpeg', 'gif'])):

          ilename, file_extension = os.path.splitext(image.filename)

          millis = int(round(time.time() * 1000))

          filename = str(millis) + file_extension

"app/static/images", filename))


      return redirect("/")



Add in Front Router:

@front.route('/registration', methods=['POST'])

def registeruser():

  return homecontroller.registeruser()

@front.route('/new', methods=['GET'])

def newpost():


@front.route('/new', methods=['POST'])

def writePost():

  return homecontroller.writePost()


Now create views inside views directory that uses jinja Template Engine.


  <title>{{ title }} - New Post</title>
    <a href="/">Home</a>   <form id="registration" method="post" enctype="multipart/form-data">
    Title: <input type="text" name="title" /><br>
    Content: <input type="text" name="content" /><br>
    Image: <input type="file" name="image" /><br>
    <button type="submit" id="btnSubmit">Submit</button>



  <title>{{ title }} - Blog</title>
    {% for post in posts: %}
    {% endfor %}

All setup is done. Open link to create new post.

All the post will view on