Quickstart

This part of the documentation shows how to use the most important parts ofWerkzeug. It’s intended as a starting point for developers with basicunderstanding of PEP 333 (WSGI) and RFC 2616 (HTTP).

Warning

Make sure to import all objects from the places the documentationsuggests. It is theoretically possible in some situations to importobjects from different locations but this is not supported.

For example MultiDict is a member of the werkzeug modulebut internally implemented in a different one.

WSGI Environment

The WSGI environment contains all the information the user request transmitsto the application. It is passed to the WSGI application but you can alsocreate a WSGI environ dict using the create_environ() helper:

  1. >>> from werkzeug.test import create_environ
  2. >>> environ = create_environ('/foo', 'http://localhost:8080/')

Now we have an environment to play around:

  1. >>> environ['PATH_INFO']
  2. '/foo'
  3. >>> environ['SCRIPT_NAME']
  4. ''
  5. >>> environ['SERVER_NAME']
  6. 'localhost'

Usually nobody wants to work with the environ directly because it is limitedto bytestrings and does not provide any way to access the form data besidesparsing that data by hand.

Enter Request

For access to the request data the Request object is much more fun.It wraps the environ and provides a read-only access to the data fromthere:

  1. >>> from werkzeug.wrappers import Request
  2. >>> request = Request(environ)

Now you can access the important variables and Werkzeug will parse themfor you and decode them where it makes sense. The default charset forrequests is set to utf-8 but you can change that by subclassingRequest.

  1. >>> request.path
  2. u'/foo'
  3. >>> request.script_root
  4. u''
  5. >>> request.host
  6. 'localhost:8080'
  7. >>> request.url
  8. 'http://localhost:8080/foo'

We can also find out which HTTP method was used for the request:

  1. >>> request.method
  2. 'GET'

This way we can also access URL arguments (the query string) and data thatwas transmitted in a POST/PUT request.

For testing purposes we can create a request object from supplied datausing the from_values() method:

  1. >>> from cStringIO import StringIO
  2. >>> data = "name=this+is+encoded+form+data&another_key=another+one"
  3. >>> request = Request.from_values(query_string='foo=bar&blah=blafasel',
  4. ... content_length=len(data), input_stream=StringIO(data),
  5. ... content_type='application/x-www-form-urlencoded',
  6. ... method='POST')
  7. ...
  8. >>> request.method
  9. 'POST'

Now we can access the URL parameters easily:

  1. >>> request.args.keys()
  2. ['blah', 'foo']
  3. >>> request.args['blah']
  4. u'blafasel'

Same for the supplied form data:

  1. >>> request.form['name']
  2. u'this is encoded form data'

Handling for uploaded files is not much harder as you can see from thisexample:

  1. def store_file(request):
  2. file = request.files.get('my_file')
  3. if file:
  4. file.save('/where/to/store/the/file.txt')
  5. else:
  6. handle_the_error()

The files are represented as FileStorage objects which providesome common operations to work with them.

Request headers can be accessed by using the headersattribute:

  1. >>> request.headers['Content-Length']
  2. '54'
  3. >>> request.headers['Content-Type']
  4. 'application/x-www-form-urlencoded'

The keys for the headers are of course case insensitive.

Header Parsing

There is more. Werkzeug provides convenient access to often used HTTP headersand other request data.

Let’s create a request object with all the data a typical web browser transmitsso that we can play with it:

  1. >>> environ = create_environ()
  2. >>> environ.update(
  3. ... HTTP_USER_AGENT='Mozilla/5.0 (Macintosh; U; Mac OS X 10.5; en-US; ) Firefox/3.1',
  4. ... HTTP_ACCEPT='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  5. ... HTTP_ACCEPT_LANGUAGE='de-at,en-us;q=0.8,en;q=0.5',
  6. ... HTTP_ACCEPT_ENCODING='gzip,deflate',
  7. ... HTTP_ACCEPT_CHARSET='ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  8. ... HTTP_IF_MODIFIED_SINCE='Fri, 20 Feb 2009 10:10:25 GMT',
  9. ... HTTP_IF_NONE_MATCH='"e51c9-1e5d-46356dc86c640"',
  10. ... HTTP_CACHE_CONTROL='max-age=0'
  11. ... )
  12. ...
  13. >>> request = Request(environ)

Let’s start with the most useless header: the user agent:

  1. >>> request.user_agent.browser
  2. 'firefox'
  3. >>> request.user_agent.platform
  4. 'macos'
  5. >>> request.user_agent.version
  6. '3.1'
  7. >>> request.user_agent.language
  8. 'en-US'

A more useful header is the accept header. With this header the browserinforms the web application what mimetypes it can handle and how well. Allaccept headers are sorted by the quality, the best item being the first:

  1. >>> request.accept_mimetypes.best
  2. 'text/html'
  3. >>> 'application/xhtml+xml' in request.accept_mimetypes
  4. True
  5. >>> print request.accept_mimetypes["application/json"]
  6. 0.8

The same works for languages:

  1. >>> request.accept_languages.best
  2. 'de-at'
  3. >>> request.accept_languages.values()
  4. ['de-at', 'en-us', 'en']

And of course encodings and charsets:

  1. >>> 'gzip' in request.accept_encodings
  2. True
  3. >>> request.accept_charsets.best
  4. 'ISO-8859-1'
  5. >>> 'utf-8' in request.accept_charsets
  6. True

Normalization is available, so you can safely use alternative forms to performcontainment checking:

  1. >>> 'UTF8' in request.accept_charsets
  2. True
  3. >>> 'de_AT' in request.accept_languages
  4. True

E-tags and other conditional headers are available in parsed form as well:

  1. >>> request.if_modified_since
  2. datetime.datetime(2009, 2, 20, 10, 10, 25)
  3. >>> request.if_none_match
  4. <ETags '"e51c9-1e5d-46356dc86c640"'>
  5. >>> request.cache_control
  6. <RequestCacheControl 'max-age=0'>
  7. >>> request.cache_control.max_age
  8. 0
  9. >>> 'e51c9-1e5d-46356dc86c640' in request.if_none_match
  10. True

Responses

Response objects are the opposite of request objects. They are used to senddata back to the client. In reality, response objects are nothing more thanglorified WSGI applications.

So what you are doing is not returning the response objects from your WSGIapplication but calling it as WSGI application inside your WSGI applicationand returning the return value of that call.

So imagine your standard WSGI “Hello World” application:

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

With response objects it would look like this:

  1. from werkzeug.wrappers import Response
  2.  
  3. def application(environ, start_response):
  4. response = Response('Hello World!')
  5. return response(environ, start_response)

Also, unlike request objects, response objects are designed to be modified.So here is what you can do with them:

  1. >>> from werkzeug.wrappers import Response
  2. >>> response = Response("Hello World!")
  3. >>> response.headers['content-type']
  4. 'text/plain; charset=utf-8'
  5. >>> response.data
  6. 'Hello World!'
  7. >>> response.headers['content-length'] = len(response.data)

You can modify the status of the response in the same way. Either just thecode or provide a message as well:

  1. >>> response.status
  2. '200 OK'
  3. >>> response.status = '404 Not Found'
  4. >>> response.status_code
  5. 404
  6. >>> response.status_code = 400
  7. >>> response.status
  8. '400 BAD REQUEST'

As you can see attributes work in both directions. So you can set bothstatus and status_code and thechange will be reflected to the other.

Also common headers are exposed as attributes or with methods to set /retrieve them:

  1. >>> response.content_length
  2. 12
  3. >>> from datetime import datetime
  4. >>> response.date = datetime(2009, 2, 20, 17, 42, 51)
  5. >>> response.headers['Date']
  6. 'Fri, 20 Feb 2009 17:42:51 GMT'

Because etags can be weak or strong there are methods to set them:

  1. >>> response.set_etag("12345-abcd")
  2. >>> response.headers['etag']
  3. '"12345-abcd"'
  4. >>> response.get_etag()
  5. ('12345-abcd', False)
  6. >>> response.set_etag("12345-abcd", weak=True)
  7. >>> response.get_etag()
  8. ('12345-abcd', True)

Some headers are available as mutable structures. For example mostof the Content- headers are sets of values:

  1. >>> response.content_language.add('en-us')
  2. >>> response.content_language.add('en')
  3. >>> response.headers['Content-Language']
  4. 'en-us, en'

Also here this works in both directions:

  1. >>> response.headers['Content-Language'] = 'de-AT, de'
  2. >>> response.content_language
  3. HeaderSet(['de-AT', 'de'])

Authentication headers can be set that way as well:

  1. >>> response.www_authenticate.set_basic("My protected resource")
  2. >>> response.headers['www-authenticate']
  3. 'Basic realm="My protected resource"'

Cookies can be set as well:

  1. >>> response.set_cookie('name', 'value')
  2. >>> response.headers['Set-Cookie']
  3. 'name=value; Path=/'
  4. >>> response.set_cookie('name2', 'value2')

If headers appear multiple times you can use the getlist()method to get all values for a header:

  1. >>> response.headers.getlist('Set-Cookie')
  2. ['name=value; Path=/', 'name2=value2; Path=/']

Finally if you have set all the conditional values, you can make theresponse conditional against a request. Which means that if the requestcan assure that it has the information already, no data besides the headersis sent over the network which saves traffic. For that you should set atleast an etag (which is used for comparison) and the date header and thencall make_conditional with the request object.

The response is modified accordingly (status code changed, response bodyremoved, entity headers removed etc.)