Last active
September 4, 2020 03:24
-
-
Save meyer1994/97550f4b572a6e7ed1e9476faf7ff4d9 to your computer and use it in GitHub Desktop.
Simple JSONRPC router with a flask-like interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Router(object): | |
def __init__(self): | |
super(Router, self).__init__() | |
self.handlers = {} | |
def method(self, name: str): | |
def wrapper(func: callable): | |
self.add_handler(name, func) | |
def wrapped(*args, **kwargs): | |
return func(*args, **kwargs) | |
return wrapped | |
return wrapper | |
def __call__(self, rpc): | |
method = rpc['method'] | |
params = rpc['params'] | |
function = self.handlers[method] | |
return function(params) | |
# Usage: | |
router = Router() | |
@router.method('nice') | |
def method(params): | |
print(params) | |
rpc = { | |
'method': 'nice', | |
'params': [1, 2] | |
} | |
router(rpc) | |
# [1, 2] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Union | |
from pydantic import BaseModel, Field, Extra | |
class BaseV2(BaseModel): | |
jsonrpc: Field(str, const=True) = '2.0' | |
class Config: | |
extra = Extra.forbid | |
class Request(BaseV2): | |
id: str | |
method: str | |
params: Union[list, dict] = None | |
class Notification(BaseV2): | |
method: str | |
params: Union[list, dict] = None | |
Batch = Union[Request, Notification] | |
class Success(BaseV2): | |
id: str | |
result: Union[dict, list, float, int, str, bool] | |
class ErrorObject(BaseModel): | |
code: int | |
message: str | |
data: Union[dict, list, float, int, str, bool] = None | |
class Error(BaseV2): | |
id: str | |
error: ErrorObject |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment