JSON-RPC Server middleware
Django and AJAX
This middleware is another attemp to simplify AJAX usage with Django based on JSON-RPC specification (http://json-rpc.org/). It inspired by Java Struts2 JSON-plugin by Musachy Barroso (http://cwiki.apache.org/S2PLUGINS/json-plugin.html) and SimpleJSONRPCServer by David McNab (http://code.djangoproject.com/wiki/JSON-RPC).
Basic configuration
- jsonrpcserver.py must be on your PYTHONPATH.
- Put class 'jsonrpcserver.JSONRPCServerMiddleware' to Django middleware list in settings.py:
MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.transaction.TransactionMiddleware', "jsonrpcserver.JSONRPCServerMiddleware", )
- Add 'jsonrpc_urlpatterns' to 'urls.py' with 'urlpatterns' syntax:
from django.conf.urls.defaults import * urlpatterns = patterns('', #standard django url configuration here #... ) jsonrpc_urlpatterns = patterns('', (r'^myapp/json_rpc_service/$', 'myapp.newapp.json_rpc_views'), (r'^myapp/json_rpc_geoservice/$', 'myapp.geo.views'), )
note: 'myapp.newapp.json_rpc_views' IS NOT A FUNCTION, BUT A MODULE, that contains exposed JSON-RPC functions.
Optional Django settings
- JSONRPC_URLPATTERNS_NAME:
Default value: 'jsonrpc_urlpatterns'. Name of the variable in 'urls.py',that contains JSON-RPC URL patterns. URL pattern must have Django syntax, but they must contain MODULES NAMES, NOT FUNCTION NAMES as second element in tuple for patterns function.
- JSONRPC_SERIALIZER:
Default value: JSONSerializer class - thin wrapper over django.utils.simplejson. Name of the JSON serializer class, that must have methods 'serialize' and 'deserialize'
- JSONRPC_JSONFY_AT_ALL_COSTS:
Default value: False. Boolean flag, that determines whether JSON encoder should throwing an error or returning a str() representation of unsupportable python object. See implementation of AugmentedJSONEncoder class.
Usage
- Write exposed function im module, listed in jsonrpc_urlpatterns:
from jsonrpcserver import jsonrpc_function @jsonrpc_function def my_python_method(par1, par2): return par1 + par2 ...
- use from JS client (e.g. dojo):
var service = new dojo.rpc.JsonService({ "serviceType": "JSON-RPC", "serviceURL": "/myapp/json_rpc_service/" }); service.callRemote("my_python_method", ["string1", "string2"]) .addCallback(...);
Example
See example here: http://alx3apps.appspot.com/jsonrpc_example/.
Sources
Sources available in google svn: http://code.google.com/p/django-json-rpc-server/
Other
Written by alx3 (alx3apps(at)gmail(dot)com). You can use this code under the terms of BSD licence (like Django project).
Attachments (1)
- jsonrpcserver.py (9.2 KB ) - added by 16 years ago.
Download all attachments as: .zip