Dup Ver Goto 📝

JSONRPC Basics 1

To
75 lines, 191 words, 1927 chars Page 'JsonRpc_01' does not exist.

These are a couple of quick experiments starting from the sample code on the python-jsonrpc site.

Server

from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple

from jsonrpc import JSONRPCResponseManager, dispatcher

@dispatcher.add_method
def foobar(**kwargs):
  print(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)
from werkzeug.wrappers import Request, Response
from werkzeug.serving import run_simple

from jsonrpc import JSONRPCResponseManager
from jsonrpc.dispatcher import Dispatcher

my_dispatcher = Dispatcher() # if we want more than one dispatcher
@d.add_method
def foobar(**kwargs):
  print(kwargs)
  return kwargs["foo"] + "==" + kwargs["bar"]

@Request.application
def application(request):
    response = JSONRPCResponseManager.handle(request.data, my_dispatcher)
    return Response(response.json, mimetype='application/json')


if __name__ == '__main__':
    run_simple('localhost', 4000, application)

Client

import requests
import json
from icecream import ic; ic.configureOutput(includeContext=True)

def main():
    url = "http://localhost:4000/jsonrpc"
    headers = {'content-type': 'application/json'}

    payload = {
        "method": "foobar",
        "params": { "random": "barf", "foo": "jelly", "bar": "icecream" },
        "jsonrpc": "2.0",
        "id": 0,
    }
    response = requests.post(
        url, data=json.dumps(payload), headers=headers).json()

    ic(response)

if __name__ == "__main__":
    main()