Examples

We start with a simple helloworld example. Before we proceed with examples let’s setup a virtualenv environment:

$ virtualenv env
$ env/bin/easy_install wheezy.http

Hello World

helloworld.py shows you how to use Wheezy HTTP in a pretty simple WSGI application:

from wheezy.http import HTTPResponse
from wheezy.http import WSGIApplication
from wheezy.http import bootstrap_http_defaults
from wheezy.http import not_found


def welcome(request):
    response = HTTPResponse()
    response.write('Hello World!!!')
    return response


def router_middleware(request, following):
    path = request.path
    if path == '/':
        response = welcome(request)
    else:
        response = not_found()
    return response


options = {}
main = WSGIApplication([
    bootstrap_http_defaults,
    lambda ignore: router_middleware
], options)


if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    try:
        print('Visit http://localhost:8080/')
        make_server('', 8080, main).serve_forever()
    except KeyboardInterrupt:
        pass
    print('\nThanks!')

Let have a look through each line in this application.

Request Handler

First of all let’s take a look what is request handler:

def welcome(request):
    response = HTTPResponse()
    response.write('Hello World!!!')
    return response

It is a simple callable of form:

def handler(request):
    return response

In Wheezy HTTP there are no dependencies between HTTPRequest and HTTPResponse.

While Wheezy HTTP doesn’t prescribe what is a router, we add here a simple router middleware. This way you can use one of available alternatives to provide route matching for your application.

def router_middleware(request, following):
    path = request.path
    if path == '/':
        response = welcome(request)
    else:
        response = not_found()
    return response

There is a separate python package wheezy.routing that is recommended way to add routing facility to your application.

Finally we create the entry point that is an instance of WSGIApplication.

options = {}
main = WSGIApplication([
    bootstrap_http_defaults,
    lambda ignore: router_middleware
], options)

The rest in the helloworld application launches a simple wsgi server. Try it by running:

$ python helloworld.py

Visit http://localhost:8080/.

Guest Book

TODO

Table Of Contents

Previous topic

Getting Started

Next topic

User Guide

This Page