Version 2 (modified by floydpetrus, 15 years ago) ( diff )

--

A simplistic json-rpc dispatcher-function for Django in 15 lines

  ### myproj/myapp/views.py

import sets
import jsonrpc


def JSON_RPC_io(object):
      methods = Set(['<method1>', '<metohod2>', '<method3>', ....])  # Set of available service method names
      rpc_inputs = jsonrpc.json.loads(object.raw_post_data)
      sub_eval = str(rpc_inputs['method']) + '(rpc_inputs[\'params\'])'
      if rpc_inputs['method'] in methods:
         result = eval(sub_eval)
         json_retur = jsonrpc.json.dumps({'result': result['result'], 'error': result['error'], 'id': rpc_inputs['id']})
         response = HttpResponse(json_retur)
         response.__setitem__('Content-Type', 'application/json-rpc')
         return response
      else:
         json_retur = jsonrpc.json.dumps({'result': None, 'error': '<non_existent_method_mesg>', 'id': rpc_inputs['id']})
         response = HttpResponse(json_retur)
         response.__setitem__('Content-Type', 'application/json-rpc')
         return response
         

This function works as a decoding/encoding dispatcher between Django's HttpRequest-object and arbitrary defined method-functions of the json-rpc service. Those method-functions shall return a dictionary-object such as {'result': <result_data>, 'error': <error_data>} . This dispatcher-function is suitable for non-public json-rpc apps handling specific data process/validate tasks.

Note: See TracWiki for help on using the wiki.
Back to Top