Simple WSGI Server Example

This example describes how to add synchronous BugScout reporting to a WSGI app. This is not intended for production use. It’s purpose is to show how easy it is to add this kind of reporting.

An example that is suitable for production is the celery extension example.

This example uses the Paste python package.

Setup a simple WSGI server

A simple paste WSGI server that can handle HTTP requests is:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""A simple WSGI server."""

from __future__ import print_function, unicode_literals


def app(environ, start_response):
    """Simple WSGI application that returns 200 OK response with 'Hellow
    world!' in the body.

    :param environ: WSGI environ
    :param start_response: function that accepts status string and headers
    """
    start_response('200 OK', [('content-type', 'text/html')])
    return ['Hellow world!']


if __name__ == '__main__':
    import paste.httpserver
    paste.httpserver.serve(app, host='0.0.0.0', port='5000')

To run this server:

python path/to/simple_wsgi.py

Making requests to http://localhost:5000/ will respond with a 200 OK and ‘Hellow world!’ in the body.

Adding BugzScout

When errors occur in this code, it would be great to report them to BugzScout. In order to so, wrap the contents of the app function in a try/except and call bugzscout in the except block.

This example creates a new function, bugzscout_app, that does just that.

import bugzscout
import sys
import traceback

# Create an instance of BugzScout to use for all errors thrown in
# bugzscout_app.
b = bugzscout.BugzScout(
    'http://fogbugz/scoutSubmit.asp', 'error-user', 'MyAppProject', 'Errors')


def bugzscout_app(environ, start_response):
    """Simple WSGI application that returns 200 OK response with 'Hellow
    world!' in the body. If an uncaught exception is thrown, it is reported to
    BugzScout.

    :param environ: WSGI environ
    :param start_response: function that accepts status string and headers
    """
    try:
        start_response('200 OK', [('content-type', 'text/html')])
        return ['Hellow world!']
    except Exception as ex:
        # Set the description to a familiar string with the exception
        # message. Add the stack trace to extra.
        b.submit_error('An error occurred in MyApp: {0}'.format(ex.message),
                       extra=traceback.extract_tb(*sys.exc_info()))

        # Reraise the exception.
        raise ex

The same __main__ block from above can be used, substituting bugzscout_app for app. When an error is thrown during a request, it will be recorded to FogBugz via BugzScout (assuming the BugzScout configuration is correctly set). Note that the request will still fail in the same way as it would above, since the exception is re-raised.

Project Versions

Table Of Contents

Previous topic

Examples Uses of BugzScout

Next topic

Example WSGI server using celery extension

This Page