Getting started quickly with Diesel for Python

Post to Twitter

Diesel is a project similar to Tornado. From the Diesel website they describe it as: “Diesel is a framework for writing network applications using asynchronous I/O in Python”. Today we will build a simple Diesel application and communicate with it via Telnet. The potential of Diesel is exciting when you begin to understand how you could use it for Comet based applications.

In order to get Diesel working you currently need Linux and Python 2.6.x. I’m using Ubuntu 9.04 under VMWare Workstation. Once you have Python installed (if its not already) you can easily install Diesel via “easy_install” (Python Cheeseshop) using this command:

sudo easy_install -UZ diesel

Its as simple as that and since Diesel is not dependent on any outside libraries apart from the Python standard library it is a very quick install. If you want the bleeding edge or you simply want to browse the latest documentation, source and example files you can find those here.

Taking some of the sample code on the Diesel website I mashed together a modified version of their echo server that can be shutdown remotely (I basically took the code from their quick start section and the section on the echo server so it should look very similar to their documentation code). Of course you wouldn’t allow remote shutdowns without someone sort of protection on a production server but for development and our testing this is fine.

from diesel import Application, Service, until, until_eol

def handle_echo(remote_addr):
    while True:
	inp = (yield until_eol())
        if inp.strip() == "quit":
        yield "you said %s" % inp

app = Application()
app.add_service(Service(handle_echo, port=8000))

Diesel Sample Code

All we do is fire up our application via the command line and listen for connections, if we get one we repeat the data back to the client. If someone sends a “quit” command we shutdown the application server. Firing up Telnet a sample session would look like this:

Connecting to Diesel via Telnet

That’s about as simple as it gets!

Post to Twitter

This entry was posted in Comet, Python, Ubuntu. Bookmark the permalink.