Help us understand the problem. What is going on with this article?

Python JSON-RPC

More than 1 year has passed since last update.

参考

・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を動かしてみた

kagami-r0927
都内に住む大学生 機械学習/業務効率化/フロント/バックエンドに興味があります。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away