Saturday, October 25, 2008

Tuesday, October 21, 2008

A Brief Pyjamas + Django Tutorial

Update: (June 19, 2009) Since the writing of this post, Pyjamas has been updated and the below code no longer works, though the principles discussed are still valid. The example code is now being maintained in the pyjamas Sourceforge repo, located here.


Django is a web framework written in Python. Pyjamas is a Python port of the google web toolkit (written in Java). Pyjamas can be used with Django to create web applications.

In terms of an MVC framework, Django acts as the Model and Pyjamas acts as the Views and Controller.

The "Todo List" Application:

In this brief tutorial, we will create a very simple todo list. The primary purpose of this tutorial is to briefly demonstrate how to serve data with Django, how to create and display widgets with Pyjamas, and how to handle user events with Pyjamas.


Here is the software that is needed:
This tutorial will not go into how to install each of these components, nor their basic usage. Hopefully, some of them can be downloaded as packages for your linux distribution. One reader recommended that you have a fairly recent Django version. > 1.0 should work.

The Code:

from django.conf.urls.defaults import *
from django.conf import settings

urlpatterns = patterns('',
(r'^services/$', 'todo.views.service'),
(r'^site_media/(?P.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC}),


import os
STATIC = str(os.path.join(os.path.dirname(__file__), 'media').replace('\\','/'))

DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'todo' # Or path to database file if using sqlite3.
DATABASE_USER = 'todo' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.



from django.db import models

class Todo(models.Model):
task = models.CharField(max_length=30)

def __unicode__(self):
return str(self.task)


from import *
from todo.models import Todo

service = JSONRPCService()

def getTasks (request):
return [(str(task), for task in Todo.objects.all()]

def addTask (request, taskFromJson):
t = Todo()
t.task = taskFromJson
return getTasks(request)

def deleteTask (request,idFromJson):
t = Todo.objects.get(id=idFromJson)
return getTasks(request)


See the download for this. It's short, but I can't figure out how to paste html into my blog. I'm lazy.


from ui import Label, RootPanel, VerticalPanel, TextBox, KeyboardListener, ListBox
from JSONService import JSONProxy

class TodoApp:
def onModuleLoad(self):
self.remote = DataService()
panel = VerticalPanel()

self.todoTextBox = TextBox()

self.todoList = ListBox()

panel.add(Label("Add New Todo:"))
panel.add(Label("Click to Remove:"))

def onKeyUp(self, sender, keyCode, modifiers):

def onKeyDown(self, sender, keyCode, modifiers):

def onKeyPress(self, sender, keyCode, modifiers):
This functon handles the onKeyPress event, and will add the item in the text box to the list when the user presses the enter key. In the future, this method will also handle the auto complete feature.
if keyCode == KeyboardListener.KEY_ENTER and sender == self.todoTextBox:
id = self.remote.addTask(sender.getText(),self)
if id<0: id =" self.remote.deleteTask(sender.getValue(sender.getSelectedIndex()),self)" method ="=" method ="=" method ="=">


python ~/python/pyjamas-0.3/builder/

A very brief walk through of how to get this running:

Extract the demo:
  • tar -xvvzf pyjamasDjango.tar.gz
Create the db:
  • mysql -u root
  • > grant all privilages to todo.* to 'todo'@'localhost'; (or possibly > grant all on todo.* to 'todo'@'localhost';)
  • > exit;
Create the tables:
  • cd pyjsDemo
  • python syncdb
Build the javascript:
  • vim media/
  • (edit this so that it points to the of pyjamas)
  • media/
Run the server:
  • python runserver
Test it out:
  • In your browser, goto:

Here are the demo source files:

Saturday, October 18, 2008

Java to Python conversion

Pyjamas is for python, what Google Web Tooklit is for Java. Pyjamas takes python code and some widget libraries and runs it through a python-to-javascript translator. The result: Coding web appliations has never been easier! JSON calls and event handling is a breeze. Little projects that I've attempted doing in the past, using libaries such as jquery, have left me writing a lot of javascript by hand, which get's ugly.

While I absolutley love pyjamas (and gwt for that matter), I really like the looks of extjs. The good news is that they have come out with extjs-gwt, which is "a Java library for building rich internet applications with GWT."

In talking with some of the folks on the pyjamas mailing list, I've gathered that the process of making pyjamas involved hand-converting the java libaries (ie widgets) of gwt from java to python. (If you look at the source code of both pyjamas and gwt, you can see that it's a pretty straight-forward conversion).

Surprisingly, pyjamas is only about 8000 lines of source code, which is relatively long. Extjs-gwt, on the other hand, as one person on the mailing list commented, has over 33,000 lines of java code in widgets alone!

The task of hand-translating extjs-gwt would be daunting.

I'm currently investigating the possiblity of writing a java to python converter to at least help out with the translation. A google search let me to a blog post which led me to an unmaintained project called java2python.

Because I'm personally interested in the workings of such technologies, and because I couldn't get java2python to work, I've decided to write my own translator.

I found a great article by the author of antlr (the same lexer/parser/tree_generator that java2python uses) on how to do such a translation between languages.

I hope that my efforts prove fruitful!

Wednesday, October 15, 2008

Remote Building on Eclipse

I recently had a need, or desire, to develop c++ code on Eclipse in windows, but have it build remotely on a specially configured linux box. Here's how I did it:

  • Get Cygwin and make sure ssh.exe and rsync.exe are installed with it.
  • I created a make.exe file out of the following (which I put in C:\WINDOWS):


main(int argc, char * argv[])

char str[200] = "make.bat";
int i = 0;
for (i = 1; i < tmp =" argv[i];">

  • I created a make.bat out of the following (which I put in C:\WINDOWS):

@echo off
set CURDIR=%cd%
chdir C:\Documents and Settings\g...ROOT OF PROJECT HERE
C:\cygwin\bin\rsync.exe -rave C:\cygwin\bin\ssh.exe . guser@
C:\cygwin\bin\ssh.exe guser@ python """%CURDIR% --- %*"""

  • On the remote machine, I created a with the following (left in my homedir). This code is highly customized, so you will probably need to modify it. What it basically does is it converts C:\.... to a linux style path.

def main():
args = sys.argv

argsFromWindows = args[1]
print "received: " + argsFromWindows

path, buildArgs = argsFromWindows.split("---")

relPath = path.split("CUST")[2].replace("\\","/").strip("/")

print "relPath: " + relPath
print "buildArgs: " + buildArgs

curDir = os.popen('cd remoteBuild/%s; make %s' % (relPath, buildArgs))

if __name__ == "__main__":

  • Now I can use eclipse's build button. It creates the makefiles locally on the machine, rsync's them over, builds them, and then spits back any errors/warnings to me.