| 1 | == A simplistic json-rpc dispatcher-function for Django in 15 lines == |
| 2 | |
| 3 | {{{ |
| 4 | ### myproj/myapp/views.py |
| 5 | |
| 6 | import sets |
| 7 | import jsonrpc |
| 8 | |
| 9 | |
| 10 | def JSON_RPC_io(object): |
| 11 | methods = Set(['<method1>', '<metohod2>', '<method3>', ....]) # Set of available service method names |
| 12 | rpc_inputs = jsonrpc.json.loads(object.raw_post_data) |
| 13 | sub_eval = str(rpc_inputs['method']) + '(rpc_inputs[\'params\'])' |
| 14 | if rpc_inputs['method'] in methods |
| 15 | result = eval(sub_eval) |
| 16 | json_retur = jsonrpc.json.dumps({'result': result['result'], 'error': result['error'], 'id': rpc_inputs['id']}) |
| 17 | response = HttpResponse(json_retur) |
| 18 | response.__setitem__('Content-Type', 'application/json-rpc') |
| 19 | return response |
| 20 | else: |
| 21 | json_retur = jsonrpc.json.dumps({'result': None, 'error': '<non_existent_method_mesg>', 'id': rpc_inputs['id']}) |
| 22 | response = HttpResponse(json_retur) |
| 23 | response.__setitem__('Content-Type', 'application/json-rpc') |
| 24 | return response |
| 25 | |
| 26 | }}} |
| 27 | |
| 28 | |
| 29 | This function works as a decoding/encoding dispatcher between Django's '''HttpRequest'''-object and |
| 30 | arbitrary defined method-functions of the json-rpc service. Those method-functions shall return a |
| 31 | dictionary-object such as '''{'result': <result_data>, 'error': <error_data>}''' . This dispatcher-function |
| 32 | is suitable for non-public json-rpc apps handling specific data process/validate tasks. |