Playing with WSGI in Python (part 1)
Lately I have been playing around with WSGI in Python. WSGI is an interface between the web server and the web application, it is meant to simplify writing your own web framework in Python. My intention is not to write an fully fledged web framework, but rather just play around with some ideas I have and try it out.
In WSGI an application is just a callable object (remember that in Python functions are objects too!) that takes two parameters, environ and start_response. A very simple application could look like this:
def application(environ, start_response):
start_response('200 OK', [('content-type', 'text/html')])
return ['Hello world!']
Not very exiting but it shows us the very basics of WSGI. The function start_response is a function that, as the name implies, starts sending out the response. This is where you give status and headers. Lastly the application returns an iterator with the body response (usually a list of strings or a list containing one string that is the entire body). As you can see WSGI lets code pass around web request in a fairly formal way.
To run this application you can either install Apache and configure it with modwsgi, this might however be slightly overkill just in order to test the application. Instead I recommend installing Python Paste (pythonpaste.com), which is kind of a framework for web frameworks. It includes a lot of functionality that can be reused, but more importantly right now, it includes a simple web server that can serve WSGI applications. In Ubuntu 9.04 (the operating system I am currently running) Paste can be installed using apt:
apt-get install python-paste
To run the application, add the folowing lines to the end of your source file:
if __name__ == '__main__':
from paste import httpserver
httpserver.serve(application, host='127.0.0.1', port='8000')
Now it should be possible to run the application:
$ python appserver.py
serving on http://127.0.0.1:8000
Your web application is now up running! In the next part i will introduce you to a slightly more exiting application.