Examples

Before we proceed let’s setup a virtualenv environment, activate it and install:

$ pip install wheezy.http

Hello World

helloworld.py shows you how to use wheezy.http in a pretty simple WSGI application:

    HTTPResponse,
    WSGIApplication,
    bootstrap_http_defaults,
    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!!!")

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()

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