Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/aiohttp/payload_streamer.py: 66%
29 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:40 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:40 +0000
1"""
2Payload implementation for coroutines as data provider.
4As a simple case, you can upload data from file::
6 @aiohttp.streamer
7 async def file_sender(writer, file_name=None):
8 with open(file_name, 'rb') as f:
9 chunk = f.read(2**16)
10 while chunk:
11 await writer.write(chunk)
13 chunk = f.read(2**16)
15Then you can use `file_sender` like this:
17 async with session.post('http://httpbin.org/post',
18 data=file_sender(file_name='huge_file')) as resp:
19 print(await resp.text())
21..note:: Coroutine must accept `writer` as first argument
23"""
25import types
26import warnings
27from typing import Any, Awaitable, Callable, Dict, Tuple
29from .abc import AbstractStreamWriter
30from .payload import Payload, payload_type
32__all__ = ("streamer",)
35class _stream_wrapper:
36 def __init__(
37 self,
38 coro: Callable[..., Awaitable[None]],
39 args: Tuple[Any, ...],
40 kwargs: Dict[str, Any],
41 ) -> None:
42 self.coro = types.coroutine(coro)
43 self.args = args
44 self.kwargs = kwargs
46 async def __call__(self, writer: AbstractStreamWriter) -> None:
47 await self.coro(writer, *self.args, **self.kwargs)
50class streamer:
51 def __init__(self, coro: Callable[..., Awaitable[None]]) -> None:
52 warnings.warn(
53 "@streamer is deprecated, use async generators instead",
54 DeprecationWarning,
55 stacklevel=2,
56 )
57 self.coro = coro
59 def __call__(self, *args: Any, **kwargs: Any) -> _stream_wrapper:
60 return _stream_wrapper(self.coro, args, kwargs)
63@payload_type(_stream_wrapper)
64class StreamWrapperPayload(Payload):
65 async def write(self, writer: AbstractStreamWriter) -> None:
66 await self._value(writer)
69@payload_type(streamer)
70class StreamPayload(StreamWrapperPayload):
71 def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None:
72 super().__init__(value(), *args, **kwargs)
74 async def write(self, writer: AbstractStreamWriter) -> None:
75 await self._value(writer)