1
0
Fork 0
bthlabs-jsonrpc/packages/bthlabs-jsonrpc-core/bthlabs_jsonrpc_core/decorators.py

38 lines
1.1 KiB
Python

# -*- coding: utf-8 -*-
# bthlabs-jsonrpc-core | (c) 2022-present Tomek Wójcik | MIT License
from __future__ import annotations
import typing
from bthlabs_jsonrpc_core.registry import MethodRegistry
def register_method(method: str,
namespace: str | None = None,
) -> typing.Callable:
"""
Registers the decorated function as JSONRPC *method* in *namespace*.
If *namespace* is omitted, the function will be registered in the default
namespace.
Example:
.. code-block:: python
@register_method('example')
def example(a, b):
return a + b
"""
if namespace is None:
namespace = MethodRegistry.DEFAULT_NAMESPACE
def decorator(handler: typing.Callable) -> typing.Callable:
registry = MethodRegistry.shared_registry()
registry.register_method(namespace, method, handler)
handler.jsonrpc_method = method # type: ignore[attr-defined]
handler.jsonrpc_namespace = namespace # type: ignore[attr-defined]
return handler
return decorator