Configure middleware
Middleware is a software component that's part of a web application, and is capable of reading and modifying inbound requests and outbound responses.
The Python agent is implemented as a middleware for all of the frameworks that Contrast supports. To use the Python agent, you must configure the middleware for the framework that your application uses:
AIOHTTP
AIOHTTP middleware is a class-based middleware that should be passed into the aiohttp web.Application
constructor as an argument. The following example shows a sample AIOHTTP application that uses the Contrast middleware class:
from aiohttp import web from contrast.aiohttp import ContrastMiddleware routes = web.RouteTableDef() @routes.get("/") def index(request): raise web.HTTPFound("/hello") middlewares = [ContrastMiddleware(app_name="app name")] app = web.Application(middlewares=middlewares) app.add_routes(routes) web.run_app(app)
Django
Old configuration steps: will not work with Contrast Python agent versions 5.0.0 and later
Django middleware is configured in the settings.py
file.
Find the
settings.py
file. This file isn't found in the same location for all applications, but it's generally near the top of the application source tree. Common locations include:/settings.py
config/settings.py
app/settings.py
Note
When searching the source tree to find the settings.py, make sure to exclude any directories that correspond to Python virtual environments.
Some applications have multiple settings.py files, which may correspond to different configurations of the application (for example, prod or test). In these cases, add the Contrast agent middleware to any and all of the configurations where it will be used.
Add the Contrast agent module to the list.
Include the Contrast middleware as early in the list as is possible; although modifying the order may be necessary to get the application working in some circumstances.
Django 1.10 and later: Look for the
MIDDLEWARE
configuration variable, which is an array. Add the Contrast agent module to the list:MIDDLEWARE = [ 'contrast.agent.middlewares.django_middleware.DjangoMiddleware', # OTHER MIDDLEWARE, ]
Django 1.6 to 1.9: Look for the
MIDDLEWARE_CLASSES
configuration variable in settings.py and add the Contrast agent module to the list:MIDDLEWARE_CLASSES = [ 'contrast.agent.middlewares.legacy_django_middleware.DjangoMiddleware', # OTHER MIDDLEWARE ]
See the Django documentation for more details on middleware inclusion.
New configuration steps: works with Contrast Python agent versions 4.6.0 and later
Contrast's Django middleware is a WSGI middleware, not a Django-style middleware.
Find your WSGI application object. The
WSGI_APPLICATION
Django configuration option points to your project's WSGI app - this is often located inwsgi.py
.A sample
wsgi.py
might look like this, whereapplication
is your WSGI application object:from django.core.wsgi import get_wsgi_application application = get_wsgi_application() <InstallContrastHere>
Wrap the WSGI application object with Contrast's middleware. In the example above, replace
<InstallContrastHere>
with:from contrast.django import ContrastMiddleware application = ContrastMiddleware(application)
FastAPI
FastAPI middleware is a class-based ASGI middleware that relies on starlette.middleware.BaseHTTPMiddleware
. Check Python supported technologies for the latest version of FastAPI supported by Contrast. The following example shows a sample FastAPI application that uses the Contrast middleware class:
from fastapi import FastAPI from contrast.fastapi import ContrastMiddleware app = FastAPI() app.add_middleware(ContrastMiddleware, original_app=app) @app.get("/") def read_root(): return RedirectResponse("/home")
If your FastAPI application uses other middleware in addition to Contrast, Contrast must be the first middleware initialized in order for certain features to work.
from fastapi import FastAPI from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware from contrast.fastapi import ContrastMiddleware app = FastAPI() # ContrastMiddleware must be the first middleware app.add_middleware(ContrastMiddleware, original_app=app) app.add_middleware(HTTPSRedirectMiddleware)
Adding middleware via the add_middleware
method is the only supported way to add middleware at this time, because certain features require the FastAPI app
to be passed in as the original_app
keyword argument. Initializing middlewares by passing them in directly to the FastAPI class initialization is not currently supported by Contrast.
# Not currently supported. app = FastAPI(middleware=[...])
Warning
Calling add_middleware
multiple times is known to re-initialize all previous middleware.
Flask
Contrast’s Flask middleware is a WSGI middleware which operates by wrapping the Flask application instance.
Find your Flask application object. This will be an instance of
flask.Flask
.A sample Flask application might look like this, where
app
is your Flask application object:import Flask app = Flask(__name__) <InstallContrastHere> @app.route('/') def index(): return render_template('index.html') app.run(...)
Wrap the Flask application object with Contrast's middleware. In the example above, replace
<InstallContrastHere>
with:from contrast.flask import ContrastMiddleware app.wsgi_app = ContrastMiddleware(app)
Note
Contrast's Flask middleware requires an instance of
flask.Flask
as an argument, rather thanflask.Flask.wsgi_app
.
Pyramid
Old configuration steps: will not work with Contrast Python agent versions 5.0.0 and later
In Pyramid, middlewares are called "tweens".
Find the configurator object in your application codebase. It might look like this:
from pyramid.config import Configurator config = Configurator() <InstallContrastHere>
Add Contrast's middleware to your config. In the example above, replace
<InstallContrastHere>
with:config.add_tween('contrast.agent.middlewares.pyramid_middleware.PyramidMiddleware')
See the Pyramid documentation for additional details on tween configuration.
New configuration steps: works with Contrast Python agent versions 4.6.0 and later
Contrast's Pyramid middleware is a WSGI middleware, not a Pyramid-style "tween".
Find your WSGI application object. This is often created by a call to
Configurator.make_wsgi_app()
.For example, it might look like this:
from pyramid.config import Configurator config = Configurator() app = config.make_wsgi_app() <InstallContrastHere>
Wrap the WSGI application object with Contrast's middleware. In the example above, replace
<InstallContrastHere>
with:from contrast.pyramid import ContrastMiddleware app = ContrastMiddleware(app)
Important
In rare cases, Contrast may require that you pass your application's Registry object to the middleware as well. The registry is commonly available as an attribute of both the Configurator instance and the Pyramid application object.
If the application does not start, find your application Registry and pass it to Contrast's middleware, for example:
app = ContrastMiddleware(app, config.registry)
Quart
The Quart middleware should wrap the Quart application object and be assigned to the asgi_app
attribute. The following example shows a sample quart application that uses the Contrast middleware class:
from quart import Quart, redirect from contrast.quart import ContrastMiddleware app = Quart(__name__) app.asgi_app = ContrastMiddleware(app) @app.route("/") async def index(): return redirect("/home")
WSGI
Contrast provides a generic WSGI middleware that includes all core agent functionality. Framework-specific features such as route discovery are not implemented in the generic WSGI middleware.
To instrument any WSGI-compliant application with Contrast:
Find the WSGI application object in your application codebase. For example, given a WSGI app created as follows:
from example.module import make_app wsgi_app = make_app() <InstallContrastHere>
Wrap the WSGI application object with Contrast's middleware. In the example above, replace
<InstallContrastHere>
with:from contrast.wsgi import ContrastMiddleware wsgi_app = ContrastMiddleware(wsgi_app)
See the WSGI specification for additional details on WSGI middleware.