Skip to content

June 4, 2009

Django with JsonRPC and XMLRPC

[Edit: take a look at RPC4Django for a JSONRPC and XMLRPC server for Django]

I corresponded recently with a developer working on a Django-powered jsonrpc library. In the past, I have done some work on web applications that require good external interfaces. In some cases, however, it makes sense to make the same methods available via both jsonrpc and xmlrpc.

For javascript and flash, json makes a lot of sense. For communication between client side and server side, jsonrpc works very well since json is natively supported and speed can be more of a factor in presentation. However, if external interfaces are also going to interact with your API, jsonrpc is not as well supported as xmlrpc. Virtually every language has good libraries for xmlrpc. For this reason, it makes good sense to combine the two and make the same methods available to both.

import logging
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse, Http404
from jsonrpc import JsonRpc

xmlrpcdispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None)
jsonrpcdispatcher = JsonRpc()
# ... register methods with xmlrpc and jsonrpc

def rpc_handler(request):
    if request.META['CONTENT_TYPE'] == 'application/json':
        response = jsonrpcdispatcher.handle_request(request)
    elif request.META['CONTENT_TYPE'] == 'text/xml':
        response = HttpResponse()
        response.write(xmlrpcdispatcher._marshaled_dispatch(request.raw_post_data))
        response['Content-length'] = str(len(response.content))
    else:
        # display documentation, or just raise a 404
        logging.debug('rpc request type: %s' %request.META['CONTENT_TYPE'])
        raise Http404

    return response
Read more from Development

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments