Version 9 (modified by 13 years ago) ( diff ) | ,
---|
A simplistic json-rpc dispatcher-function for Django in 15 lines
Security warning
This code contains a security issue! It uses eval() on the json data coming from the client without first cleaning it. This makes it possible for an attacker to run arbitrary code on the server.
The code
### myproj/myapp/views.py import json jsonrpc_methods = [] def JSON_RPC_dispatcher(obj): rpc_inputs = json.loads(obj.raw_post_data) sub_eval = str(rpc_inputs['method']) + '(rpc_inputs["params"])' if rpc_inputs['method'] in jsonrpc_methods: # WARNING: Executing eval() on untrusted data result = eval(sub_eval) json_retur = 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 = 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 as {'result': <result_data>, 'error': <error_data>} and their names shall be appended/registered to the jsonrpc_methods list. This dispatcher-function is generally suitable for any json-rpc app and neutral to the exact version of the json-rpc protocol in consideration.