Last active
July 5, 2016 02:49
-
-
Save ochinchina/e7ea0da594dca56731cc9c1ae35c8451 to your computer and use it in GitHub Desktop.
json rpc in python
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 requests | |
import json | |
def main(): | |
url = "http://localhost:4000/jsonrpc" | |
headers = {'content-type': 'application/json'} | |
# Example echo method | |
payload = { | |
"method": "echo", | |
"params": ["echome!"], | |
"jsonrpc": "2.0", | |
"id": 0, | |
} | |
response = requests.post( | |
url, data=json.dumps(payload), headers=headers).json() | |
assert response["result"] == "echome!" | |
assert response["jsonrpc"] | |
assert response["id"] == 0 | |
payload = { | |
"method": "foobar", | |
"params": {"foo":"dummy","bar":"beer"}, | |
"jsonrpc": "2.0", | |
"id": 0, | |
} | |
response = requests.post( | |
url, data=json.dumps(payload), headers=headers).json() | |
print response | |
if __name__ == "__main__": | |
main() |
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
from werkzeug.wrappers import Request, Response | |
from werkzeug.serving import run_simple | |
from jsonrpc import JSONRPCResponseManager, dispatcher | |
@dispatcher.add_method | |
def foobar(**kwargs): | |
return kwargs["foo"] + kwargs["bar"] | |
@Request.application | |
def application(request): | |
# Dispatcher is dictionary {<method_name>: callable} | |
dispatcher["echo"] = lambda s: s | |
dispatcher["add"] = lambda a, b: a + b | |
response = JSONRPCResponseManager.handle( | |
request.data, dispatcher) | |
return Response(response.json, mimetype='application/json') | |
if __name__ == '__main__': | |
run_simple('localhost', 4000, application) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment