source code bean

10 Aug, 2009

Playing with WSGI in Python (part 1)

Posted by: Peter In: Linux|Python|Web

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:

  1.  
  2. def application(environ, start_response):
  3.    start_response(’200 OK’, [(‘content-type’, ‘text/html’)])
  4.    return [‘Hello world!’]
  5.  

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:

  1. apt-get install python-paste

To run the application, add the folowing lines to the end of your source file:

  1.  
  2. if __name__ == ‘__main__’:
  3.   from paste import httpserver
  4.   httpserver.serve(application, host=’127.0.0.1′, port=’8000′)
  5.  

Now it should be possible to run the application:

  1.  
  2. $ python appserver.py
  3. serving on http://127.0.0.1:8000
  4.  

Your web application is now up running! In the next part i will introduce you to a slightly more exiting application.



No Responses to "Playing with WSGI in Python (part 1)"

Comment Form

Adwords

About

Welcome to source code bean! On this site I post stuff that I encounter in my job and spare time. The content is mostly related to .NET development, but my interest in techonology is very broad, so often you will find posts on totally different subjects!