コード例 #1
0
ファイル: factories.py プロジェクト: unmade/apiwrappers
 async def fetch(
         self,
         request: Request,
         timeout: Union[Timeout, NoValue] = NoValue(),
 ) -> Response:
     # pylint: disable=unused-argument
     return dataclasses.replace(self.response, request=request)
コード例 #2
0
ファイル: shortcuts.py プロジェクト: unmade/apiwrappers
def fetch(
    driver: AsyncDriver,
    request: Request,
    timeout: _Timeout = NoValue(),
    model: Union[Callable[..., T], Type[T]] = None,
    source: Optional[str] = None,
) -> Awaitable[T]:
    ...
コード例 #3
0
ファイル: shortcuts.py プロジェクト: unmade/apiwrappers
def fetch(
    driver: AsyncDriver,
    request: Request,
    timeout: _Timeout = NoValue(),
    model: None = None,
    source: Optional[str] = None,
) -> Awaitable[Response]:
    ...
コード例 #4
0
ファイル: shortcuts.py プロジェクト: unmade/apiwrappers
def fetch(
    driver: Driver,
    request: Request,
    timeout: _Timeout = NoValue(),
    model: None = None,
    source: Optional[str] = None,
) -> Response:
    ...
コード例 #5
0
ファイル: protocols.py プロジェクト: unmade/apiwrappers
    async def fetch(
        self,
        request: Request,
        timeout: Union[Timeout, NoValue] = NoValue(),
    ) -> Response:
        """
        Makes actual request and returns response from the server.

        Args:
            request: a request object with data to send to server.
            timeout: how many seconds to wait for the server to send data before
                giving up. If set to ``None`` waits infinitely. If provided, will take
                precedence over the :py:attr:`AsyncDriver.timeout`.

        Returns: response from the server.

        Raises:
            Timeout: the request timed out.
            ssl.SSLError: An SSL error occurred.
            ConnectionFailed: a connection error occurred.
            DriverError: in case of any other error in driver underlying library.
        """
        ...
コード例 #6
0
    def fetch(
            self,
            request: Request,
            timeout: Union[Timeout, NoValue] = NoValue(),
    ) -> Response:
        try:
            response = requests.request(
                request.method.value,
                str(request.url),
                params=request.query_params,
                headers=request.headers,
                cookies=request.cookies,
                data=request.data,
                files=request.files,
                json=request.json,
                timeout=self._prepare_timeout(timeout),
                verify=self.verify,
                cert=self.cert,
            )
        except requests.Timeout as exc:
            raise exceptions.Timeout from exc
        except requests.exceptions.SSLError as exc:
            raise ssl.SSLError(str(exc)) from exc
        except requests.ConnectionError as exc:
            raise exceptions.ConnectionFailed from exc
        except requests.RequestException as exc:
            raise exceptions.DriverError from exc

        return Response(
            request=request,
            status_code=int(response.status_code),
            url=response.url,
            headers=CaseInsensitiveDict(response.headers),
            cookies=SimpleCookie(response.cookies),
            encoding=response.encoding or "utf-8",
            content=response.content,
        )
コード例 #7
0
    async def fetch(
        self,
        request: Request,
        timeout: Union[Timeout, NoValue] = NoValue(),
    ) -> Response:
        async with aiohttp.ClientSession() as session:
            try:
                response = await session.request(
                    request.method.value,
                    str(request.url),
                    headers=request.headers,
                    cookies=request.cookies,
                    params=self._prepare_query_params(request.query_params),
                    data=self._prepare_data(request),
                    json=request.json,
                    timeout=self._prepare_timeout(timeout),
                    ssl=self._prepare_ssl(),
                )
            except asyncio.TimeoutError as exc:
                raise exceptions.Timeout from exc
            except aiohttp.ClientSSLError as exc:
                raise ssl.SSLError(str(exc)) from exc
            except aiohttp.ClientConnectionError as exc:
                raise exceptions.ConnectionFailed from exc
            except aiohttp.ClientError as exc:
                raise exceptions.DriverError from exc

            return Response(
                request=request,
                status_code=int(response.status),
                url=str(response.url),
                headers=CaseInsensitiveDict(response.headers),
                cookies=SimpleCookie(response.cookies),
                content=await response.read(),
                encoding=response.get_encoding(),
            )
コード例 #8
0
        "name": "apiwrappers",
        "tags": ["api", "client"],
        "pre-release": True,
        "version": 1,
    }

    client = HttpBin(httpbin.url, driver=aiohttp_driver())
    response = await client.post(json=payload)
    assert response.json()["json"] == payload  # type: ignore


@pytest.mark.parametrize(
    ["driver_timeout", "fetch_timeout", "expected"],
    [
        (None, None, None),
        (None, NoValue(), None),
        (None, 0.5, 0.5),
        (300, None, None),
        (300, 1, 1),
        (300, NoValue(), 300),
        (timedelta(minutes=1), NoValue(), 60),
        (None, timedelta(minutes=1), 60),
    ],
)
async def test_timeout(driver_timeout, fetch_timeout, expected) -> None:
    driver = aiohttp_driver(timeout=driver_timeout)
    wrapper = HttpBin("https://httpbin.org", driver=driver)
    target = "aiohttp.client.ClientSession.request"
    with mock.patch(target, side_effect=mock_request) as request_mock:
        await wrapper.delay(2, fetch_timeout)
    _, call_kwargs = request_mock.call_args
コード例 #9
0
ファイル: protocols.py プロジェクト: unmade/apiwrappers
 def __call__(
     self,
     request: Request,
     timeout: Union[Timeout, NoValue] = NoValue(),
 ) -> Awaitable[Response]:
     ...
コード例 #10
0
ファイル: protocols.py プロジェクト: unmade/apiwrappers
 def __call__(
     self,
     request: Request,
     timeout: Union[Timeout, NoValue] = NoValue(),
 ) -> Response:
     ...
コード例 #11
0
ファイル: base.py プロジェクト: unmade/apiwrappers
 def __call__(self, request, timeout=NoValue()):
     if iscoroutinehandler(self.handler):
         call_next = self.call_next_async
     else:
         call_next = self.call_next
     return call_next(self.handler, request, timeout=timeout)
コード例 #12
0
ファイル: base.py プロジェクト: unmade/apiwrappers
 def __call__(
     self: BaseMiddleware[AsyncHandler],
     request: Request,
     timeout: Union[Timeout, NoValue] = NoValue(),
 ) -> Awaitable[Response]:
     ...
コード例 #13
0
ファイル: base.py プロジェクト: unmade/apiwrappers
 def __call__(
     self: BaseMiddleware[Handler],
     request: Request,
     timeout: Union[Timeout, NoValue] = NoValue(),
 ) -> Response:
     ...
コード例 #14
0
ファイル: shortcuts.py プロジェクト: unmade/apiwrappers
# pylint: disable=too-many-arguments

import asyncio
from typing import Awaitable, Callable, Optional, Type, TypeVar, Union, overload

from apiwrappers import utils
from apiwrappers.entities import Request, Response
from apiwrappers.protocols import AsyncDriver, Driver
from apiwrappers.structures import NoValue
from apiwrappers.typedefs import Timeout

T = TypeVar("T")

_Timeout = Union[Timeout, NoValue]

NO_VALUE = NoValue()


@overload
def fetch(
    driver: Driver,
    request: Request,
    timeout: _Timeout = NoValue(),
    model: None = None,
    source: Optional[str] = None,
) -> Response:
    ...


@overload
def fetch(
コード例 #15
0
def test_representation_no_value():
    assert repr(NoValue()) == "NoValue()"