Skip to content

Instantly share code, notes, and snippets.

@yangacer
Created June 10, 2015 10:10
Show Gist options
  • Save yangacer/c8e1d65f37b155688f1d to your computer and use it in GitHub Desktop.
Save yangacer/c8e1d65f37b155688f1d to your computer and use it in GitHub Desktop.
JSONRPC over HTTP client invoker (within requests library)
import json
import requests
import functools
"""
Example:
cli = jsonrpc('http://rpcserver.com:6666')
try:
resp = cli.echo(hello='world')
except JSONRPCError as e:
print repr(e)
"""
class JSONRPCError(Exception):
pass
class jsonrpc(object):
def __init__(self, url):
self.url = url
pass
def __getattr__(self, method):
return functools.partial(jsonrpc.invoke_, self.url, method)
@staticmethod
def invoke_(url, method, **params):
headers = {'Content-Type' : 'application/json' }
payload = dict(id=1,
jsonrpc="2.0",
method=method,
params=params)
resp = requests.post(url, data=json.dumps(payload), headers=headers)
resp = resp.json()
if 'error' in resp:
raise JSONRPCError(str(resp['error']))
return resp['result']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment