Created
June 10, 2015 10:10
-
-
Save yangacer/c8e1d65f37b155688f1d to your computer and use it in GitHub Desktop.
JSONRPC over HTTP client invoker (within requests library)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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