LoginSignup
2
3

More than 5 years have passed since last update.

Python JSON-RPC

Last updated at Posted at 2018-09-28

参考

・json-rpc Quick start
https://json-rpc.readthedocs.io/en/latest/quickstart.html

必要なパッケージのインストール

$ pip install json-rpc
$ pip install werkzeug
$ pip install requests

以下のファイルを作成します。

sever.py
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)
client.py
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

if __name__ == "__main__":
    main()

作成できたら実行していきます。

$ python server.py
 * Running on http://localhost:4000/ (Press CTRL+C to quit)

別のタブを開いて、実行してください。

$ python client.py

そうすると、server.pyをrunしたタブの方で、

127.0.0.1 - - [28/Sep/2018 16:29:30] "POST /jsonrpc HTTP/1.1" 200 -

と出力されるはずです。

次回

JSON-RPC使って、gethを動かしてみた

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3