API Levels

Werkzeug is intended to be a utility rather than a framework. Because of thatthe user-friendly API is separated from the lower-level API so that Werkzeugcan easily be used to extend another system.

All the functionality the Request and Response objects (akathe “wrappers”) provide is also available in small utility functions.

Example

This example implements a small Hello World application that greets theuser with the name entered:

  1. from werkzeug.utils import escape
  2. from werkzeug.wrappers import Request, Response
  3.  
  4. @Request.application
  5. def hello_world(request):
  6. result = ['<title>Greeter</title>']
  7. if request.method == 'POST':
  8. result.append('<h1>Hello %s!</h1>' % escape(request.form['name']))
  9. result.append('''
  10. <form action="" method="post">
  11. <p>Name: <input type="text" name="name" size="20">
  12. <input type="submit" value="Greet me">
  13. </form>
  14. ''')
  15. return Response(''.join(result), mimetype='text/html')

Alternatively the same application could be used without request and responseobjects but by taking advantage of the parsing functions werkzeug provides:

  1. from werkzeug.formparser import parse_form_data
  2. from werkzeug.utils import escape
  3.  
  4. def hello_world(environ, start_response):
  5. result = ['<title>Greeter</title>']
  6. if environ['REQUEST_METHOD'] == 'POST':
  7. form = parse_form_data(environ)[1]
  8. result.append('<h1>Hello %s!</h1>' % escape(form['name']))
  9. result.append('''
  10. <form action="" method="post">
  11. <p>Name: <input type="text" name="name" size="20">
  12. <input type="submit" value="Greet me">
  13. </form>
  14. ''')
  15. start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
  16. return [''.join(result).encode('utf-8')]

High or Low?

Usually you want to use the high-level layer (the request and responseobjects). But there are situations where this might not be what you want.

For example you might be maintaining code for an application written inDjango or another framework and you have to parse HTTP headers. You canutilize Werkzeug for that by accessing the lower-level HTTP header parsingfunctions.

Another situation where the low level parsing functions can be useful arecustom WSGI frameworks, unit-testing or modernizing an old CGI/mod_pythonapplication to WSGI as well as WSGI middlewares where you want to keep theoverhead low.