1.2 An Example

Programming with httpy means writing responders. To whet your whistle, here is httpy's hello world:

>>> from httpy import Response
>>> class Responder:
...   def respond(self, request):
...     return Response(200, "Greetings, program!")
...
>>>

A responder is simply a module or class with a respond callable, which takes a Request object and raises a Response object. Besides being a subclass of StandardError, Response is bone simple: its constructor takes an integer HTTP code, a body, and a dictionary of headers - all optional. At the end of the transaction, this response is returned back up the stack towards the client.

As mentioned, responders can also raise Responses. So, for example, you might add a check on the incoming method:

>>> class Responder:
...   def respond(self, request):
...     if request.method != 'GET':
...       raise Response(501)
...     return Response(200, "Greetings, program!")
...
>>>

In any case, after defining a responder, here is how to put it on the network:

>>> from httpy.couplers.standalone import Coupler
>>> coupler = Coupler(Responder())
>>> coupler.go()
INFO     server.py:126 httpy started on port 8080

At this point, your program is blocking, waiting for requests on http://localhost:8080/. Visit it there, and you will see the text Greetings, program! in your browser, and log output in your console. Congratulations!

httpy is Zeta software. It is copyright © 2006 by Chad Whitacre, and is offered free of charge, warranty, and restrictions.