Skip to content

Werkzeug

Werkzeug is the WSGI toolkit under Flask. Use it on its own for a small WSGI app:

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

from jsonrpcserver import Result, Success, dispatch, method


class JsonRpcRequest(Request):
    # Bigger requests get 413 Request Entity Too Large.
    max_content_length = 1_000_000


@method
def ping() -> Result:
    return Success("pong")


@JsonRpcRequest.application
def application(request: JsonRpcRequest) -> Response:
    # max_batch_size: see the Security page.
    if response := dispatch(request.get_data(as_text=True), max_batch_size=100):
        return Response(response, content_type="application/json")
    return Response(status=204)


if __name__ == "__main__":
    run_simple("localhost", 8000, application)

Setting max_content_length on a Request subclass makes get_data refuse a bigger body with 413. max_batch_size limits how many requests one batch can hold. See Security.

To give methods the request, pass it as context: dispatch(..., context=request). See Context.

run_simple is Werkzeug's development server. For production, use a WSGI server such as Gunicorn.

Try it

Save the example as werkzeug_server.py, install Werkzeug (pip install werkzeug), and run it:

python werkzeug_server.py

Then send it a request from another terminal:

curl -s -H 'Content-Type: application/json' -d '{"jsonrpc": "2.0", "method": "ping", "id": 1}' http://localhost:8000/
Output
{"jsonrpc": "2.0", "result": "pong", "id": 1}

The jsonrpcclient quickstart sends the same request from Python.