aiohttp-rpc


Nameaiohttp-rpc JSON
Version 1.3.1 PyPI version JSON
download
home_pagehttps://github.com/expert-m/aiohttp-rpc/
SummaryA simple JSON-RPC for aiohttp
upload_time2023-10-15 08:22:35
maintainer
docs_urlNone
authorMichael Sulyak
requires_python>=3.7
licenseMIT license
keywords aiohttp asyncio json-rpc rpc
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # aiohttp-rpc

[![PyPI](https://img.shields.io/pypi/v/aiohttp-rpc.svg?style=flat)](https://pypi.org/project/aiohttp-rpc/)
[![PyPI - Python Version](https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10%20%7C%203.11-blue?style=flat)](https://www.python.org/downloads/release/python-380/)
[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/expert-m/aiohttp-rpc.svg?style=flat)](https://scrutinizer-ci.com/g/expert-m/aiohttp-rpc/?branch=master)
[![GitHub Issues](https://img.shields.io/github/issues/expert-m/aiohttp-rpc.svg?style=flat)](https://github.com/expert-m/aiohttp-rpc/issues)
[![Gitter](https://img.shields.io/gitter/room/aiohttp-rpc/Lobby)](https://gitter.im/aiohttp-rpc/Lobby)
[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://opensource.org/licenses/MIT)

> A library for a simple integration of the [JSON-RPC 2.0 protocol](https://www.jsonrpc.org/specification) to a Python application using [aiohttp](https://github.com/aio-libs/aiohttp).
The motivation is to provide a simple, fast and reliable way to integrate the JSON-RPC 2.0 protocol into your application on the server and/or client side.
<br/><br/>
>The library has only one dependency:
>* **[aiohttp](https://github.com/aio-libs/aiohttp)** - Async http client/server framework

## Table Of Contents
- **[Installation](#installation)**
    - **[pip](#pip)**
- **[Usage](#usage)**
  - **[HTTP Server Example](#http-server-example)**
  - **[HTTP Client Example](#http-client-example)**
- [Integration](#Integration)
- [Middleware](#middleware)
- [WebSockets](#websockets)
  - [WS Server Example](#ws-server-example)
  - [WS Client Example](#ws-client-example)
- [API Reference](#api-reference)
- [More examples](#more-examples)
- [License](#license)

## Installation

#### pip
```sh
pip install aiohttp-rpc
```

## Usage

### HTTP Server Example

```python3
from aiohttp import web
import aiohttp_rpc


def echo(*args, **kwargs):
    return {
        'args': args,
        'kwargs': kwargs,
    }

# If the function has rpc_request in arguments, then it is automatically passed
async def ping(rpc_request):
    return 'pong'


if __name__ == '__main__':
    aiohttp_rpc.rpc_server.add_methods([
        ping,
        echo,
    ])

    app = web.Application()
    app.router.add_routes([
        web.post('/rpc', aiohttp_rpc.rpc_server.handle_http_request),
    ])
    web.run_app(app, host='0.0.0.0', port=8080)
```

### HTTP Client Example
```python3
import aiohttp_rpc
import asyncio

async def run():
    async with aiohttp_rpc.JsonRpcClient('http://0.0.0.0:8080/rpc') as rpc:
        print('#1', await rpc.ping())
        print('#2', await rpc.echo('one', 'two'))
        print('#3', await rpc.call('echo', three='3'))
        print('#4', await rpc.notify('echo', 123))
        print('#5', await rpc.get_methods())
        print('#6', await rpc.batch([
            ['echo', 2], 
            'echo2',
            'ping',
        ]))

loop = asyncio.get_event_loop()
loop.run_until_complete(run())
```

This prints:
```text
#1 pong
#2 {'args': ['one', 'two'], 'kwargs': {}}
#3 {'args': [], 'kwargs': {'three': '3'}}
#4 None
#5 {'get_method': {'doc': None, 'args': ['name'], 'kwargs': []}, 'get_methods': {'doc': None, 'args': [], 'kwargs': []}, 'ping': {'doc': None, 'args': ['rpc_request'], 'kwargs': []}, 'echo': {'doc': None, 'args': [], 'kwargs': []}}
#6 ({'args': [2], 'kwargs': {}}, JsonRpcError(-32601, 'The method does not exist / is not available.'), 'pong')
```

[back to top](#table-of-contents)

---

<p align="center"><b>↑ This is enough to start :sunglasses: ↑</b></p>

---


## Integration

The purpose of this library is to simplify life, and not vice versa.
And so, when you start adding existing functions, some problems may arise.

Existing functions can return objects that are not serialized, but this is easy to fix.
You can write own `json_serialize`:
```python3
from aiohttp import web
import aiohttp_rpc
import uuid
import json
from dataclasses import dataclass
from functools import partial

@dataclass
class User:  # The object that is not serializable.
    uuid: uuid.UUID
    username: str = 'mike'
    email: str = 'some@mail.com'

async def get_user_by_uuid(user_uuid) -> User:
    # Some function which returns not serializable object.
    # For example, data may be taken from a database.
    return User(uuid=uuid.UUID(user_uuid))


def json_serialize_unknown_value(value):
    if isinstance(value, User):
        return {
            'uuid': str(value.uuid),
            'username': value.username,
            'email': value.email,
        }

    return repr(value)

if __name__ == '__main__':
    rpc_server = aiohttp_rpc.JsonRpcServer(
        json_serialize=partial(json.dumps, default=json_serialize_unknown_value),
    )
    rpc_server.add_method(get_user_by_uuid)
    
    app = web.Application()
    app.router.add_routes([
        web.post('/rpc', rpc_server.handle_http_request),
    ])
    web.run_app(app, host='0.0.0.0', port=8080)
...

"""
Example of response:
{
    "id": 1,
    "jsonrpc": "2.0",
    "result": {
        "uuid": "600d57b3-dda8-43d0-af79-3e81dbb344fa",
        "username": "mike",
        "email": "some@mail.com"
    }
}
"""
```

But you can go further.
If you want to use functions that accept custom types,
then you can do something like this:
```python3
# The function (RPC method) that takes a custom type.
def generate_user_token(user: User):
    return f'token-{str(user.uuid).split("-")[0]}'

async def replace_type(data):
    if not isinstance(data, dict) or '__type__' not in data:
        return data

    if data['__type__'] == 'user':
        return await get_user_by_uuid(data['uuid'])

    raise aiohttp_rpc.errors.InvalidParams

# The middleware that converts types
async def type_conversion_middleware(request, handler):
    request.set_args_and_kwargs(
        args=[await replace_type(arg) for arg in request.args],
        kwargs={key: await replace_type(value) for key, value in request.kwargs.items()},
    )
    return await handler(request)


rpc_server = aiohttp_rpc.JsonRpcServer(middlewares=[
    aiohttp_rpc.middlewares.exception_middleware,
    aiohttp_rpc.middlewares.extra_args_middleware,
    type_conversion_middleware,
])

"""
Request:
{
    "id": 1234,
    "jsonrpc": "2.0",
    "method": "generate_user_token",
    "params": [{"__type__": "user", "uuid": "600d57b3-dda8-43d0-af79-3e81dbb344fa"}]
}

Response:
{
    "id": 1234,
    "jsonrpc": "2.0",
    "result": "token-600d57b3"
}
"""
```

[Middleware](#middleware) allows you to replace arguments, responses, and more.

If you want to add permission checking for each method,
then you can override the class `JsonRpcMethod` or use [middleware](#middleware).

[back to top](#table-of-contents)

---


## Middleware

Middleware is used for [RPC Request / RPC Response](#protocol) processing.
It has a similar interface as [aiohttp middleware](https://docs.aiohttp.org/en/stable/web_advanced.html#middlewares).

```python3
import aiohttp_rpc
import typing

async def simple_middleware(request: aiohttp_rpc.JsonRpcRequest, handler: typing.Callable) -> aiohttp_rpc.JsonRpcResponse:
    # Code to be executed for each RPC request before
    # the method (and later middleware) are called.

    response = await handler(request)

    # Code to be executed for each RPC request / RPC response after
    # the method is called.

    return response

rpc_server = aiohttp_rpc.JsonRpcServer(middlewares=[
     aiohttp_rpc.middlewares.exception_middleware,
     simple_middleware,
])
```

Or use [aiohttp middlewares](https://docs.aiohttp.org/en/stable/web_advanced.html#middlewares) to process `web.Request`/`web.Response`.

[back to top](#table-of-contents)

---


## WebSockets

### WS Server Example

```python3
from aiohttp import web
import aiohttp_rpc


async def ping(rpc_request):
    return 'pong'


if __name__ == '__main__':
    rpc_server = aiohttp_rpc.WsJsonRpcServer(
        middlewares=aiohttp_rpc.middlewares.DEFAULT_MIDDLEWARES,
    )
    rpc_server.add_method(ping)

    app = web.Application()
    app.router.add_routes([
        web.get('/rpc', rpc_server.handle_http_request),
    ])
    app.on_shutdown.append(rpc_server.on_shutdown)
    web.run_app(app, host='0.0.0.0', port=8080)
```

### WS Client Example
```python3
import aiohttp_rpc
import asyncio

async def run():
    async with aiohttp_rpc.WsJsonRpcClient('http://0.0.0.0:8080/rpc') as rpc:
        print(await rpc.ping())
        print(await rpc.notify('ping'))
        print(await rpc.batch([
            ['echo', 2], 
            'echo2',
            'ping',
        ]))

loop = asyncio.get_event_loop()
loop.run_until_complete(run())
```

[back to top](#table-of-contents)

---

## API Reference


### `server`
  * `class JsonRpcServer(BaseJsonRpcServer)`
    * `def __init__(self, *, json_serialize=json_serialize, middlewares=(), methods=None)`
    * `def add_method(self, method, *, replace=False) -> JsonRpcMethod`
    * `def add_methods(self, methods, replace=False) -> typing.List[JsonRpcMethod]`
    * `def get_method(self, name) -> Optional[Mapping]`
    * `def get_methods(self) -> Mapping[str, Mapping]`
    * `async def handle_http_request(self, http_request: web.Request) -> web.Response`
 
  * `class WsJsonRpcServer(BaseJsonRpcServer)`
  * `rpc_server: JsonRpcServer`
  

### `client`
  * `class JsonRpcClient(BaseJsonRpcClient)`
    * `async def connect(self)`
    * `async def disconnect(self)`
    * `async def call(self, method: str, *args, **kwargs)`
    * `async def notify(self, method: str, *args, **kwargs)`
    * `async def batch(self, methods])`
    * `async def batch_notify(self, methods)`
  
  * `class WsJsonRpcClient(BaseJsonRpcClient)`

### `protocol`
  * `class JsonRpcRequest`
    * `id: Union[int, str, None]`
    * `method: str`
    * `jsonrpc: str`
    * `extra_args: MutableMapping`
    * `context: MutableMapping`
    * `params: Any`
    * `args: Optional[Sequence]`
    * `kwargs: Optional[Mapping]`
    * `is_notification: bool`
    
  * `class JsonRpcResponse`
    * `id: Union[int, str, None]`
    * `jsonrpc: str`
    * `result: Any`
    * `error: Optional[JsonRpcError]`
    * `context: MutableMapping`
    
  * `class JsonRpcMethod(BaseJsonRpcMethod)`
    * `def __init__(self, func, *, name=None, add_extra_args=True, prepare_result=None)`
  
  * `class JsonRpcUnlinkedResults`

  * `class JsonRpcDuplicatedResults`

### `decorators`
  * `def rpc_method(*, rpc_server=default_rpc_server, name=None, add_extra_args=True)`

### `errors`
  * `class JsonRpcError(RuntimeError)`
  * `class ServerError(JsonRpcError)`
  * `class ParseError(JsonRpcError)`
  * `class InvalidRequest(JsonRpcError)`
  * `class MethodNotFound(JsonRpcError)`
  * `class InvalidParams(JsonRpcError)`
  * `class InternalError(JsonRpcError)`
  * `DEFAULT_KNOWN_ERRORS`
  
### `middlewares`
  * `async def extra_args_middleware(request, handler)`
  * `async def exception_middleware(request, handler)`
  * `DEFAULT_MIDDLEWARES`

### `utils`
  * `def json_serialize(*args, **kwargs)`

### `constants`
  * `NOTHING`
  * `VERSION_2_0`

[back to top](#table-of-contents)

---


## More examples

**The library allows you to add methods in many ways:**
```python3
import aiohttp_rpc

def ping_1(rpc_request): return 'pong 1'
def ping_2(rpc_request): return 'pong 2'
def ping_3(rpc_request): return 'pong 3'

rpc_server = aiohttp_rpc.JsonRpcServer()
rpc_server.add_method(ping_1)  # 'ping_1'
rpc_server.add_method(aiohttp_rpc.JsonRpcMethod(ping_2))  # 'ping_2'
rpc_server.add_method(aiohttp_rpc.JsonRpcMethod(ping_3, name='third_ping'))  # 'third_ping'
rpc_server.add_methods([ping_3])  # 'ping_3'

# Replace method
rpc_server.add_method(ping_1, replace=True)  # 'ping_1'
rpc_server.add_methods([ping_1, ping_2], replace=True)  # 'ping_1', 'ping_2'
```

**Example with built-in functions:**
```python3
# Server
import aiohttp_rpc

rpc_server = aiohttp_rpc.JsonRpcServer(middlewares=[aiohttp_rpc.middlewares.extra_args_middleware])
rpc_server.add_method(sum)
rpc_server.add_method(aiohttp_rpc.JsonRpcMethod(zip, prepare_result=list))
...

# Client
async with aiohttp_rpc.JsonRpcClient('/rpc') as rpc:
    assert await rpc.sum([1, 2, 3]) == 6
    assert await rpc.zip(['a', 'b'], [1, 2]) == [['a', 1], ['b', 2]]
```

**Example with the decorator:**
```python3
import aiohttp_rpc
from aiohttp import web

@aiohttp_rpc.rpc_method()
def echo(*args, **kwargs):
    return {
        'args': args,
        'kwargs': kwargs,
    }

if __name__ == '__main__':
    app = web.Application()
    app.router.add_routes([
        web.post('/rpc', aiohttp_rpc.rpc_server.handle_http_request),
    ])
    web.run_app(app, host='0.0.0.0', port=8080)
```

**It is possible to pass params into aiohttp request via `direct_call`/`direct_batch`:**
```python3
import aiohttp_rpc

jsonrpc_request = aiohttp_rpc.JsonRpcRequest(method_name='test', params={'test_value': 1})
async with aiohttp_rpc.JsonRpcClient('/rpc') as rpc:
    await rpc.direct_call(jsonrpc_request, headers={'My-Customer-Header': 'custom value'}, timeout=10)
```

[back to top](#table-of-contents)

---


## License
MIT

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/expert-m/aiohttp-rpc/",
    "name": "aiohttp-rpc",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "aiohttp,asyncio,json-rpc,rpc",
    "author": "Michael Sulyak",
    "author_email": "michael@sulyak.info",
    "download_url": "https://files.pythonhosted.org/packages/77/c6/3d7d7100fc8d7fd997cd412e3327cfa957ffec2b32acad75da20970a1fd1/aiohttp-rpc-1.3.1.tar.gz",
    "platform": null,
    "description": "# aiohttp-rpc\n\n[![PyPI](https://img.shields.io/pypi/v/aiohttp-rpc.svg?style=flat)](https://pypi.org/project/aiohttp-rpc/)\n[![PyPI - Python Version](https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10%20%7C%203.11-blue?style=flat)](https://www.python.org/downloads/release/python-380/)\n[![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/expert-m/aiohttp-rpc.svg?style=flat)](https://scrutinizer-ci.com/g/expert-m/aiohttp-rpc/?branch=master)\n[![GitHub Issues](https://img.shields.io/github/issues/expert-m/aiohttp-rpc.svg?style=flat)](https://github.com/expert-m/aiohttp-rpc/issues)\n[![Gitter](https://img.shields.io/gitter/room/aiohttp-rpc/Lobby)](https://gitter.im/aiohttp-rpc/Lobby)\n[![License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](https://opensource.org/licenses/MIT)\n\n> A library for a simple integration of the [JSON-RPC 2.0 protocol](https://www.jsonrpc.org/specification) to a Python application using [aiohttp](https://github.com/aio-libs/aiohttp).\nThe motivation is to provide a simple, fast and reliable way to integrate the JSON-RPC 2.0 protocol into your application on the server and/or client side.\n<br/><br/>\n>The library has only one dependency:\n>* **[aiohttp](https://github.com/aio-libs/aiohttp)** - Async http client/server framework\n\n## Table Of Contents\n- **[Installation](#installation)**\n    - **[pip](#pip)**\n- **[Usage](#usage)**\n  - **[HTTP Server Example](#http-server-example)**\n  - **[HTTP Client Example](#http-client-example)**\n- [Integration](#Integration)\n- [Middleware](#middleware)\n- [WebSockets](#websockets)\n  - [WS Server Example](#ws-server-example)\n  - [WS Client Example](#ws-client-example)\n- [API Reference](#api-reference)\n- [More examples](#more-examples)\n- [License](#license)\n\n## Installation\n\n#### pip\n```sh\npip install aiohttp-rpc\n```\n\n## Usage\n\n### HTTP Server Example\n\n```python3\nfrom aiohttp import web\nimport aiohttp_rpc\n\n\ndef echo(*args, **kwargs):\n    return {\n        'args': args,\n        'kwargs': kwargs,\n    }\n\n# If the function has rpc_request in arguments, then it is automatically passed\nasync def ping(rpc_request):\n    return 'pong'\n\n\nif __name__ == '__main__':\n    aiohttp_rpc.rpc_server.add_methods([\n        ping,\n        echo,\n    ])\n\n    app = web.Application()\n    app.router.add_routes([\n        web.post('/rpc', aiohttp_rpc.rpc_server.handle_http_request),\n    ])\n    web.run_app(app, host='0.0.0.0', port=8080)\n```\n\n### HTTP Client Example\n```python3\nimport aiohttp_rpc\nimport asyncio\n\nasync def run():\n    async with aiohttp_rpc.JsonRpcClient('http://0.0.0.0:8080/rpc') as rpc:\n        print('#1', await rpc.ping())\n        print('#2', await rpc.echo('one', 'two'))\n        print('#3', await rpc.call('echo', three='3'))\n        print('#4', await rpc.notify('echo', 123))\n        print('#5', await rpc.get_methods())\n        print('#6', await rpc.batch([\n            ['echo', 2], \n            'echo2',\n            'ping',\n        ]))\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(run())\n```\n\nThis prints:\n```text\n#1 pong\n#2 {'args': ['one', 'two'], 'kwargs': {}}\n#3 {'args': [], 'kwargs': {'three': '3'}}\n#4 None\n#5 {'get_method': {'doc': None, 'args': ['name'], 'kwargs': []}, 'get_methods': {'doc': None, 'args': [], 'kwargs': []}, 'ping': {'doc': None, 'args': ['rpc_request'], 'kwargs': []}, 'echo': {'doc': None, 'args': [], 'kwargs': []}}\n#6 ({'args': [2], 'kwargs': {}}, JsonRpcError(-32601, 'The method does not exist / is not available.'), 'pong')\n```\n\n[back to top](#table-of-contents)\n\n---\n\n<p align=\"center\"><b>\u2191 This is enough to start :sunglasses: \u2191</b></p>\n\n---\n\n\n## Integration\n\nThe purpose of this library is to simplify life, and not vice versa.\nAnd so, when you start adding existing functions, some problems may arise.\n\nExisting functions can return objects that are not serialized, but this is easy to fix.\nYou can write own `json_serialize`:\n```python3\nfrom aiohttp import web\nimport aiohttp_rpc\nimport uuid\nimport json\nfrom dataclasses import dataclass\nfrom functools import partial\n\n@dataclass\nclass User:  # The object that is not serializable.\n    uuid: uuid.UUID\n    username: str = 'mike'\n    email: str = 'some@mail.com'\n\nasync def get_user_by_uuid(user_uuid) -> User:\n    # Some function which returns not serializable object.\n    # For example, data may be taken from a database.\n    return User(uuid=uuid.UUID(user_uuid))\n\n\ndef json_serialize_unknown_value(value):\n    if isinstance(value, User):\n        return {\n            'uuid': str(value.uuid),\n            'username': value.username,\n            'email': value.email,\n        }\n\n    return repr(value)\n\nif __name__ == '__main__':\n    rpc_server = aiohttp_rpc.JsonRpcServer(\n        json_serialize=partial(json.dumps, default=json_serialize_unknown_value),\n    )\n    rpc_server.add_method(get_user_by_uuid)\n    \n    app = web.Application()\n    app.router.add_routes([\n        web.post('/rpc', rpc_server.handle_http_request),\n    ])\n    web.run_app(app, host='0.0.0.0', port=8080)\n...\n\n\"\"\"\nExample of response:\n{\n    \"id\": 1,\n    \"jsonrpc\": \"2.0\",\n    \"result\": {\n        \"uuid\": \"600d57b3-dda8-43d0-af79-3e81dbb344fa\",\n        \"username\": \"mike\",\n        \"email\": \"some@mail.com\"\n    }\n}\n\"\"\"\n```\n\nBut you can go further.\nIf you want to use functions that accept custom types,\nthen you can do something like this:\n```python3\n# The function (RPC method) that takes a custom type.\ndef generate_user_token(user: User):\n    return f'token-{str(user.uuid).split(\"-\")[0]}'\n\nasync def replace_type(data):\n    if not isinstance(data, dict) or '__type__' not in data:\n        return data\n\n    if data['__type__'] == 'user':\n        return await get_user_by_uuid(data['uuid'])\n\n    raise aiohttp_rpc.errors.InvalidParams\n\n# The middleware that converts types\nasync def type_conversion_middleware(request, handler):\n    request.set_args_and_kwargs(\n        args=[await replace_type(arg) for arg in request.args],\n        kwargs={key: await replace_type(value) for key, value in request.kwargs.items()},\n    )\n    return await handler(request)\n\n\nrpc_server = aiohttp_rpc.JsonRpcServer(middlewares=[\n    aiohttp_rpc.middlewares.exception_middleware,\n    aiohttp_rpc.middlewares.extra_args_middleware,\n    type_conversion_middleware,\n])\n\n\"\"\"\nRequest:\n{\n    \"id\": 1234,\n    \"jsonrpc\": \"2.0\",\n    \"method\": \"generate_user_token\",\n    \"params\": [{\"__type__\": \"user\", \"uuid\": \"600d57b3-dda8-43d0-af79-3e81dbb344fa\"}]\n}\n\nResponse:\n{\n    \"id\": 1234,\n    \"jsonrpc\": \"2.0\",\n    \"result\": \"token-600d57b3\"\n}\n\"\"\"\n```\n\n[Middleware](#middleware) allows you to replace arguments, responses, and more.\n\nIf you want to add permission checking for each method,\nthen you can override the class `JsonRpcMethod` or use [middleware](#middleware).\n\n[back to top](#table-of-contents)\n\n---\n\n\n## Middleware\n\nMiddleware is used for [RPC Request / RPC Response](#protocol) processing.\nIt has a similar interface as [aiohttp middleware](https://docs.aiohttp.org/en/stable/web_advanced.html#middlewares).\n\n```python3\nimport aiohttp_rpc\nimport typing\n\nasync def simple_middleware(request: aiohttp_rpc.JsonRpcRequest, handler: typing.Callable) -> aiohttp_rpc.JsonRpcResponse:\n    # Code to be executed for each RPC request before\n    # the method (and later middleware) are called.\n\n    response = await handler(request)\n\n    # Code to be executed for each RPC request / RPC response after\n    # the method is called.\n\n    return response\n\nrpc_server = aiohttp_rpc.JsonRpcServer(middlewares=[\n     aiohttp_rpc.middlewares.exception_middleware,\n     simple_middleware,\n])\n```\n\nOr use [aiohttp middlewares](https://docs.aiohttp.org/en/stable/web_advanced.html#middlewares) to process `web.Request`/`web.Response`.\n\n[back to top](#table-of-contents)\n\n---\n\n\n## WebSockets\n\n### WS Server Example\n\n```python3\nfrom aiohttp import web\nimport aiohttp_rpc\n\n\nasync def ping(rpc_request):\n    return 'pong'\n\n\nif __name__ == '__main__':\n    rpc_server = aiohttp_rpc.WsJsonRpcServer(\n        middlewares=aiohttp_rpc.middlewares.DEFAULT_MIDDLEWARES,\n    )\n    rpc_server.add_method(ping)\n\n    app = web.Application()\n    app.router.add_routes([\n        web.get('/rpc', rpc_server.handle_http_request),\n    ])\n    app.on_shutdown.append(rpc_server.on_shutdown)\n    web.run_app(app, host='0.0.0.0', port=8080)\n```\n\n### WS Client Example\n```python3\nimport aiohttp_rpc\nimport asyncio\n\nasync def run():\n    async with aiohttp_rpc.WsJsonRpcClient('http://0.0.0.0:8080/rpc') as rpc:\n        print(await rpc.ping())\n        print(await rpc.notify('ping'))\n        print(await rpc.batch([\n            ['echo', 2], \n            'echo2',\n            'ping',\n        ]))\n\nloop = asyncio.get_event_loop()\nloop.run_until_complete(run())\n```\n\n[back to top](#table-of-contents)\n\n---\n\n## API Reference\n\n\n### `server`\n  * `class JsonRpcServer(BaseJsonRpcServer)`\n    * `def __init__(self, *, json_serialize=json_serialize, middlewares=(), methods=None)`\n    * `def add_method(self, method, *, replace=False) -> JsonRpcMethod`\n    * `def add_methods(self, methods, replace=False) -> typing.List[JsonRpcMethod]`\n    * `def get_method(self, name) -> Optional[Mapping]`\n    * `def get_methods(self) -> Mapping[str, Mapping]`\n    * `async def handle_http_request(self, http_request: web.Request) -> web.Response`\n \n  * `class WsJsonRpcServer(BaseJsonRpcServer)`\n  * `rpc_server: JsonRpcServer`\n  \n\n### `client`\n  * `class JsonRpcClient(BaseJsonRpcClient)`\n    * `async def connect(self)`\n    * `async def disconnect(self)`\n    * `async def call(self, method: str, *args, **kwargs)`\n    * `async def notify(self, method: str, *args, **kwargs)`\n    * `async def batch(self, methods])`\n    * `async def batch_notify(self, methods)`\n  \n  * `class WsJsonRpcClient(BaseJsonRpcClient)`\n\n### `protocol`\n  * `class JsonRpcRequest`\n    * `id: Union[int, str, None]`\n    * `method: str`\n    * `jsonrpc: str`\n    * `extra_args: MutableMapping`\n    * `context: MutableMapping`\n    * `params: Any`\n    * `args: Optional[Sequence]`\n    * `kwargs: Optional[Mapping]`\n    * `is_notification: bool`\n    \n  * `class JsonRpcResponse`\n    * `id: Union[int, str, None]`\n    * `jsonrpc: str`\n    * `result: Any`\n    * `error: Optional[JsonRpcError]`\n    * `context: MutableMapping`\n    \n  * `class JsonRpcMethod(BaseJsonRpcMethod)`\n    * `def __init__(self, func, *, name=None, add_extra_args=True, prepare_result=None)`\n  \n  * `class JsonRpcUnlinkedResults`\n\n  * `class JsonRpcDuplicatedResults`\n\n### `decorators`\n  * `def rpc_method(*, rpc_server=default_rpc_server, name=None, add_extra_args=True)`\n\n### `errors`\n  * `class JsonRpcError(RuntimeError)`\n  * `class ServerError(JsonRpcError)`\n  * `class ParseError(JsonRpcError)`\n  * `class InvalidRequest(JsonRpcError)`\n  * `class MethodNotFound(JsonRpcError)`\n  * `class InvalidParams(JsonRpcError)`\n  * `class InternalError(JsonRpcError)`\n  * `DEFAULT_KNOWN_ERRORS`\n  \n### `middlewares`\n  * `async def extra_args_middleware(request, handler)`\n  * `async def exception_middleware(request, handler)`\n  * `DEFAULT_MIDDLEWARES`\n\n### `utils`\n  * `def json_serialize(*args, **kwargs)`\n\n### `constants`\n  * `NOTHING`\n  * `VERSION_2_0`\n\n[back to top](#table-of-contents)\n\n---\n\n\n## More examples\n\n**The library allows you to add methods in many ways:**\n```python3\nimport aiohttp_rpc\n\ndef ping_1(rpc_request): return 'pong 1'\ndef ping_2(rpc_request): return 'pong 2'\ndef ping_3(rpc_request): return 'pong 3'\n\nrpc_server = aiohttp_rpc.JsonRpcServer()\nrpc_server.add_method(ping_1)  # 'ping_1'\nrpc_server.add_method(aiohttp_rpc.JsonRpcMethod(ping_2))  # 'ping_2'\nrpc_server.add_method(aiohttp_rpc.JsonRpcMethod(ping_3, name='third_ping'))  # 'third_ping'\nrpc_server.add_methods([ping_3])  # 'ping_3'\n\n# Replace method\nrpc_server.add_method(ping_1, replace=True)  # 'ping_1'\nrpc_server.add_methods([ping_1, ping_2], replace=True)  # 'ping_1', 'ping_2'\n```\n\n**Example with built-in functions:**\n```python3\n# Server\nimport aiohttp_rpc\n\nrpc_server = aiohttp_rpc.JsonRpcServer(middlewares=[aiohttp_rpc.middlewares.extra_args_middleware])\nrpc_server.add_method(sum)\nrpc_server.add_method(aiohttp_rpc.JsonRpcMethod(zip, prepare_result=list))\n...\n\n# Client\nasync with aiohttp_rpc.JsonRpcClient('/rpc') as rpc:\n    assert await rpc.sum([1, 2, 3]) == 6\n    assert await rpc.zip(['a', 'b'], [1, 2]) == [['a', 1], ['b', 2]]\n```\n\n**Example with the decorator:**\n```python3\nimport aiohttp_rpc\nfrom aiohttp import web\n\n@aiohttp_rpc.rpc_method()\ndef echo(*args, **kwargs):\n    return {\n        'args': args,\n        'kwargs': kwargs,\n    }\n\nif __name__ == '__main__':\n    app = web.Application()\n    app.router.add_routes([\n        web.post('/rpc', aiohttp_rpc.rpc_server.handle_http_request),\n    ])\n    web.run_app(app, host='0.0.0.0', port=8080)\n```\n\n**It is possible to pass params into aiohttp request via `direct_call`/`direct_batch`:**\n```python3\nimport aiohttp_rpc\n\njsonrpc_request = aiohttp_rpc.JsonRpcRequest(method_name='test', params={'test_value': 1})\nasync with aiohttp_rpc.JsonRpcClient('/rpc') as rpc:\n    await rpc.direct_call(jsonrpc_request, headers={'My-Customer-Header': 'custom value'}, timeout=10)\n```\n\n[back to top](#table-of-contents)\n\n---\n\n\n## License\nMIT\n",
    "bugtrack_url": null,
    "license": "MIT license",
    "summary": "A simple JSON-RPC for aiohttp",
    "version": "1.3.1",
    "project_urls": {
        "GitHub: issues": "https://github.com/expert-m/aiohttp-rpc/issues",
        "GitHub: repo": "https://github.com/expert-m/aiohttp-rpc",
        "Homepage": "https://github.com/expert-m/aiohttp-rpc/"
    },
    "split_keywords": [
        "aiohttp",
        "asyncio",
        "json-rpc",
        "rpc"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4e2dfb72bb571cdc77d1bccffbee886595c988e5dcf908240f2ae51a3539e0bb",
                "md5": "ac33f75c6af988b0633f9b594d36c79d",
                "sha256": "1f873b34e2a491d208f0b2ed6632c3157244c945abec1471f84b37beb1e309ca"
            },
            "downloads": -1,
            "filename": "aiohttp_rpc-1.3.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ac33f75c6af988b0633f9b594d36c79d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 24481,
            "upload_time": "2023-10-15T08:22:33",
            "upload_time_iso_8601": "2023-10-15T08:22:33.281489Z",
            "url": "https://files.pythonhosted.org/packages/4e/2d/fb72bb571cdc77d1bccffbee886595c988e5dcf908240f2ae51a3539e0bb/aiohttp_rpc-1.3.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "77c63d7d7100fc8d7fd997cd412e3327cfa957ffec2b32acad75da20970a1fd1",
                "md5": "23fe6ae5ddc0e9c459035e9d77249470",
                "sha256": "462fffcb516e912c2a666578931bded3febb5d52ddbaa543f78ad4c578e381cd"
            },
            "downloads": -1,
            "filename": "aiohttp-rpc-1.3.1.tar.gz",
            "has_sig": false,
            "md5_digest": "23fe6ae5ddc0e9c459035e9d77249470",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 26480,
            "upload_time": "2023-10-15T08:22:35",
            "upload_time_iso_8601": "2023-10-15T08:22:35.636630Z",
            "url": "https://files.pythonhosted.org/packages/77/c6/3d7d7100fc8d7fd997cd412e3327cfa957ffec2b32acad75da20970a1fd1/aiohttp-rpc-1.3.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-10-15 08:22:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "expert-m",
    "github_project": "aiohttp-rpc",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "aiohttp-rpc"
}
        
Elapsed time: 0.12703s