Passed
Push — master ( 9a8b07...1de29a )
by Michael
03:47
created

aiohttp_rpc.client.http.JsonRpcClient.disconnect()   A

Complexity

Conditions 2

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 2
nop 1
1
import typing
2
3
import aiohttp
4
5
from .base import BaseJsonRpcClient
6
from .. import errors, utils
7
8
9
__all__ = (
10
    'JsonRpcClient',
11
)
12
13
14
class JsonRpcClient(BaseJsonRpcClient):
15
    url: str
16
    session: typing.Optional[aiohttp.ClientSession]
17
    request_kwargs: dict
18
    _is_outer_session: bool
19
20
    def __init__(self,
21
                 url: str, *,
22
                 session: typing.Optional[aiohttp.ClientSession] = None,
23
                 **request_kwargs) -> None:
24
        self.url = url
25
        self.session = session
26
        self.request_kwargs = request_kwargs
27
        self._is_outer_session = session is not None
28
29
    async def connect(self) -> None:
30
        if not self.session:
31
            self.session = aiohttp.ClientSession(json_serialize=self.json_serialize)
32
33
    async def disconnect(self) -> None:
34
        if not self._is_outer_session:
35
            await self.session.close()
36
37
    async def send_json(self,
38
                        data: typing.Any, *,
39
                        without_response: bool = False) -> typing.Tuple[typing.Any, typing.Optional[dict]]:
40
        http_response = await self.session.post(self.url, json=data, **self.request_kwargs)
41
42
        try:
43
            json_response = await http_response.json()
44
        except aiohttp.ContentTypeError as e:
45
            raise errors.ParseError(utils.get_exc_message(e)) from e
46
47
        if without_response:
48
            return None, None
49
50
        return json_response, {'http_response': http_response}
51