Step 0: A Basic WSGI Introduction

Werkzeug is a utility library for WSGI. WSGI itself is a protocol or convention that ensures that your web application can speak with the webserver and more importantly that web applications work nicely together.

A basic “Hello World” application in WSGI without the help of Werkzeug looks like this:

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    return ['Hello World!']

A WSGI application is something you can call and pass an environ dict and a start_responsecallable. The environ contains all incoming information, the start_response function can be used to indicate the start of the response. With Werkzeug you don’t have to deal directly with either as request and response objects are provided to work with them.

The request data takes the environ object and allows you to access the data from that environ in a nice manner. The response object is a WSGI application in itself and provides a much nicer way to create responses.

Here is how you would write that application with response objects:

from werkzeug.wrappers import Response

def application(environ, start_response):
    response = Response('Hello World!', mimetype='text/plain')
    return response(environ, start_response)

And here an expanded version that looks at the query string in the URL (more importantly at the nameparameter in the URL to substitute “World”  against another word):

from werkzeug.wrappers import Request, Response

def application(environ, start_response):
    request = Request(environ)
    text = 'Hello %s!' % request.args.get('name', 'World')
    response = Response(text, mimetype='text/plain')
    return response(environ, start_response)

And that’s all you need to know about WSGI.