Using a Python Wrapper with Contrast

  • Updated

Manual middleware configuration is no longer recommended.

Instead, you should run your application with the contrast-python-run command, which automatically detects and enables framework-specific instrumentation.

See Contrast Runner for more information.

Additionally, for use in a Kubernetes environment, the Contrast Agent Operator now supports Python applications.

For rarer cases where manual middleware configuration is still required, and the wrapper option is desired, instructions are listed below.


Lower the friction associated with instrumenting the Contrast Python agent. That is, use a wrapper script instead of modifying an application's source code.


The Contrast Python agent has very specific requirements. First, customers should check to make sure that their version of the Python language is supported. Next, a middleware component or application framework is required.  

Typical Python agent deployments require modifying the application's source code to account for the middleware component. 

Configuring the Middleware Component

Each middleware component has slightly different instructions and libraries necessary to successfully instrument the agent into a Python application. You can find middleware specific instructions here:



If your application does not use a middleware component or uses a different application framework, it is likely not a good candidate for instrumentation with Contrast Assess/Protect.

Python Wrapper Script

The alternative is to create a Python wrapper script so that the main Python application does not have to be modified. The wrapper script includes the library component necessary for the middleware mentioned above and then calls the Python application. If you don't use Flask, you'll need to modify the example to include the appropriate library as well as your main application/module name.
from contrast.flask import ContrastMiddleware # Vulpy uses Flask instead of pure wsgi

main_module_name = ''
main_function_name = 'main'

main_module = importlib.import_module(main_module_name)
main_func = getattr(main_module, main_function_name)

app.wsgi_app = ContrastMiddleware(main_func())



This alternative provides a method to allow customers to instrument the Contrast agent into their Python applications without modifying the main Python application. The primary use case for this technique is the instrumentation of Contrast in the Continuous Deployment (CD) phase of a Pipeline. A typical deployment may use Kubernetes or Tekton and therefore requires a technique that python developers prefer which means not modifying the original source to include the Contrast agent. 

Was this article helpful?

0 out of 0 found this helpful

Have more questions? Submit a request