Skip to main content

WSGI Microservice Middleware

This little library contains middlewares to help quickly turn wsgi apps (e.g., flask, django, bottle, tornado, pyramid) into production-ready microservices for integration into a kubernetes cluster. These middelewares set up to be configurable warfrom environment variables in accordance with the twelve-factor app methodology.

Middlewares in this package include:

This project spun out of development for the Presalytics as way to quickly port code across various microserivces built on wsgi-supported frameworks.

View on Github

Installation

This project requires python 3.5+. It is best installed fromt he pypi package repository via pip.

pip install wsgi_microservice_middleware

The latest branch of this package can also be installed from git:

pip install git+https://github.com/presalytics/WSGI-Microservice-Middleware

Configuration

Package configuration is best done by adding configuration values via environment varialble. This package uses the environs package to load the following values from the system environment or a .env file in the the working directory:

  • CORS_ALLOWED: Comma-separated string of domain names that will from which CORS requests can be made. Is empty by default

  • REQUEST_ID_HEADER: The http request header containing a the request-id to including in logs. If not supplied, defaults to X-Request-Id.

  • LOG_TOKENS: Instructs RequestIdMiddleware to add Bearer Authentication tokens to request logs when available. Defaults to True.

Usage

These middleware are applied by wrapping the wsgi application object in you code by the middleware class. Examples below:

  • Flask:

    # app.py
    from flask import Flask
    from wsgi_microservice_middleware.cors import CORSMiddleware
    
    app = Flask(__name__)
    app.wsgi_app = CORSMiddleware(app.wsgi_app) # Middleware applied here
    app.run(...) 
    
  • Django:

    # wsgi.py
    from django.core.wsgi import get_wsgi_application
    from wsgi_microservice_middleware.request_id import RequestIdMiddleware
    
    application = get_wsgi_application()
    application = RequestIdMiddleware(application) # Middleware applied here
    

Modules

CORS

Adds CORS headers to the responses of request that originate from domains in the CORS_ALLOWED environment variable. CORS_ALLOWED should reside in the environment as a comma-separated string of domain names.

Request Id

Implements Request Id handling for requests that need to be tracked accross multiple microservices and searched in log records. The RequestIdMiddleware class.

To extend the request Id to your application logs, incorporate the RequestIdFilter into your logging configuration. the best way to do this is to use logging.config.dictConfig to apply the filter to all of your handlers:

# log_config.py
from logging.config import dictConfig
from wsgi_microservice_middleware.request_id import RequestIdFilter


dictConfig({
    'version': 1,
    'filters': {
        'request_id_filter' : {
            '()': RequestIdFilter,  # RequestIdFilter.filter(self, record) called with each log entry
        }
    },
    'formatters': {'default': {
        'format': '%(asctime)s - %(threadName)s - %(name)s - %(levelname)s - %(request_id)s -  %(message)s',
    }},
    'handlers': {
        'wsgi': {
            'class': 'logging.StreamHandler',
            'formatter': 'default',
            'filters': ['request_id_filter']  # add this filter to each handler
        },
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['wsgi']
    }
})

If your microservice makes requests to other microservices, you can call the current_request_id() method to get the current request id and incorporate it into your request headers.

Contributing

We'd love your help! Open an issue at the github repo. Or even better, you can fork the repo and we'll merge your improvements.

Metadata

Release files for wsgi-microservice-middleware 0.1.6

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for wsgi-microservice-middleware 0.1.6
File Size Uploaded
wsgi_microservice_middleware-0.1.6.tar.gz 5.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for wsgi-microservice-middleware 0.1.6
File Interpreter ABI Platform
wsgi_microservice_middleware-0.1.6-py3-none-any.whl Python 3 none any Details

Total release size: 11.4 kB

Release files / wsgi_microservice_middleware-0.1.6.tar.gz

Download URL wsgi_microservice_middleware-0.1.6.tar.gz
Size 5.3 kB
Tags Source
SHA-256 checksum
How to use checksums
aa2ee494e9d60043c0bf411e6febcd007935c6d3d56b75a30e191d787209e107
BLAKE2b-256 checksum
How to use checksums
3fa460ab4285449313a65634f21b1358e5c2dbbe3115cd43e72c516ed6195cdd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.0.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.6.9

Release files / wsgi_microservice_middleware-0.1.6-py3-none-any.whl

Download URL wsgi_microservice_middleware-0.1.6-py3-none-any.whl
Size 6.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ecb11052e5ac3dfcadc83ccfa1f5d98decfea684815f9b71dc466b58bd8383df
BLAKE2b-256 checksum
How to use checksums
c9f64b5e818c835a6f7067a4d55dfb7e55d0e66902df363d912981fb34c2278e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.0.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.6.9

Release history Release notifications | RSS feed

This release

0.1.6 This release

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page