February 10th, 2012

Working with Pyjamas and Dajaxice

Tutorial for: Pyjamas


This short tutorial explains how to call Djaxice functions directly from Pyjamas and use the returned context.

I enjoy building web application using both Pyjamas and Django and recently found out how easy it is to build AJAX calls in Django using Dajaxice. I then thought to myself, would it be nice to use the Dajaxice facility within my Pyjamas app? Then I went off and created this reusable Pyjamas class:

# -*- coding: utf-8 -*-
from pyjamas.HTTPRequest import HTTPRequest
from pyjamas.Cookies import getCookie
from pyjamas.JSONParser import JSONParser

parser = JSONParser()
dumps = getattr(parser, 'encode')
loads = getattr(parser, 'decodeAsObject')

class JSONRequest(HTTPRequest):
  def __init__(self, callback, error_func):
    self.callback = callback
    self.onError = error_func
  def onCompletion(self, json_str):
    data = loads(json_str)
  def call(self, url, postData={}):
    remote_url = '/dajaxice/%s/' % url
    send_data = 'argv=%s' % dumps(postData)
    self.asyncPost(remote_url, send_data, self, headers=headers)

Using this code in your Pyjamas app is very easy, here is how simple it is to integrate:

from Dajaxice import JSONRequest

class MyApp(object):
  def __init__(self):
    ajax = JSONRequest(self, self.onError)
  def onCompletion(self, data):
    # Play with the data context returned from Django.
  def onError(self):
    Window.alert('An error occured.')

Read the API guide on HTTPRequest for information on how to configure the onError correctly.

There you have it, now you can easily fetch a native Django context using Djaxice directly in Pyjamas.

About Me

My Photo
Names Kevin, hugely into UNIX technologies, not just Linux. I've dabbled with the demons, played with the Sun, and now with the Penguins.

Kevin Veroneau Consulting Services
Do you require the services of a Django contractor? Do you need both a website and hosting services? Perhaps I can help.

This Month

If you like what you read, please consider donating to help with hosting costs, and to fund future books to review.

Python Powered | © 2012-2019 Kevin Veroneau