Skip to main content
This is a pre-production deployment of Warehouse. Changes made here affect the production instance of PyPI (
Help us improve Python packaging - Donate today!

Python module to add general middleware

Project Description

Copyright (c) 2016 David Betz


pip install middleware


Python 2 and 3


Most everyone needs a concept of middleware.

Following are examples of using this, see for full examples.

class AdditionMiddleware1(Middleware):
    def create(self):
        def func(mwa, context):
                counter = context['counter']
                counter = 0
            context['counter'] = counter + 1

            return next(mwa)

        return func

When using a class, add a create function which returns a function. This inner fuction accepts the middleware array and the data context and returns next(mwa) to create a middleware chain.

For this example, I’ll add two more:

class AdditionMiddleware2(AdditionMiddleware1):

class AdditionMiddleware3(AdditionMiddleware2):

Now to run it. Use set to set an array of middleware and add to add one to the array. set overwrites everything. That’s just what set means.

handler = Handler()
handler.set([AdditionMiddleware1, AdditionMiddleware2])

# handler['counter'] == 3

In this case, there is no initial context and each of the three middleware increment a counter ending with handler['counter'] == 3.

You can skip the entire class stuff too:

handler = Handler()
def inline(wma, context):
    context['myvalue'] = 12
# handler['myvalue'] == 12

Use the following to send initial context:

handler = Handler(counter=1)

It’s actually kwargs, so you can load it up:

handler = Handler(**{'a': 1, 'b': 2})
def inline(wma, context):
    context['a'] = context['a'] + context['b']
Release History

Release History

This version
History Node


History Node


History Node


History Node


Download Files

Download Files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

File Name & Checksum SHA256 Checksum Help Version File Type Upload Date
middleware-1.2.3.tar.gz (4.2 kB) Copy SHA256 Checksum SHA256 Source Jul 18, 2017

Supported By

WebFaction WebFaction Technical Writing Elastic Elastic Search Pingdom Pingdom Monitoring Dyn Dyn DNS Sentry Sentry Error Logging CloudAMQP CloudAMQP RabbitMQ Heroku Heroku PaaS Kabu Creative Kabu Creative UX & Design Fastly Fastly CDN DigiCert DigiCert EV Certificate Rackspace Rackspace Cloud Servers DreamHost DreamHost Log Hosting