How to create a middleware in Flask?

 Sudhi S.
Aug 7, 2017 · 2 min read

This article is just for beginners or those who want to create a middleware for their Python Flask Application.

Table Of Content

  1. Requirements
  2. What is middleware
  3. Why we need middleware
  4. Steps to create a Simple Middleware which call on every request.
  5. Is any other way to do the same Task like log every request , user session check etc..

Requirements

Before going to read this application you need a flask application.

What is middleware

Middleware is computer software that provides services to software applications

Why we need middleware

For example if you want to log every request middleware may useful in that case.

Client → Server → Middleware → Server side Application

Steps to create a Simple Middleware which call on every request

Step 1: create a file with name loggermiddleware.py

Step 2: add the below code

class LoggerMiddleware(object):def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
print ‘ — — — — — — — — — — -’
print ‘Function called’
print ‘ — — — — — — — — — — -’
return self.app(environ, start_response)

Step 3: modify your app.

app = Flask(__name__)
app.wsgi_app = middleware.Loggermiddleware(app.wsgi_app)

Is any other way to do the same Task like log every request , user session check etc..

Yes, Don’t worry you can fo the same task in another way without creating a middleware .

How? 👷

Use Decorator

Do you still think about how to create a Decorator?

from functools import wraps
from flask import g, request, redirect, url_for

def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
@app.route('/secret_page')
@login_required
def secret_page():
pass

For more about Decorators : http://flask.pocoo.org/docs/0.12/patterns/viewdecorators/

 Sudhi S.

Written by

Android Developer | iOS Developer | Blogger

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade