Skip to content

Commit

Permalink
Annotate client (#3092)
Browse files Browse the repository at this point in the history
* Annotate client

* Add changenote

* Drop Python 3.6 specific annotation
  • Loading branch information
asvetlov authored Jun 19, 2018
1 parent 69f5c56 commit 5d5bb46
Show file tree
Hide file tree
Showing 6 changed files with 117 additions and 85 deletions.
1 change: 1 addition & 0 deletions CHANGES/3092.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add type hints to HTTP client
63 changes: 37 additions & 26 deletions aiohttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
import sys
import traceback
import warnings
from collections.abc import Coroutine
from collections.abc import Coroutine as CoroutineABC
from typing import Any, Generator, Optional, Tuple

import attr
from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr
Expand All @@ -25,7 +26,7 @@
from .client_reqrep import ClientRequest, ClientResponse, _merge_ssl_params
from .client_ws import ClientWebSocketResponse
from .connector import * # noqa
from .connector import TCPConnector
from .connector import BaseConnector, TCPConnector
from .cookiejar import CookieJar
from .helpers import (DEBUG, PY_36, CeilTimeout, TimeoutHandle,
proxies_from_env, sentinel, strip_auth_from_url)
Expand All @@ -34,6 +35,7 @@
from .streams import FlowControlDataQueue
from .tcp_helpers import tcp_cork, tcp_nodelay
from .tracing import Trace
from .typedefs import StrOrURL


__all__ = (client_exceptions.__all__ + # noqa
Expand Down Expand Up @@ -137,7 +139,7 @@ def __init__(self, *, connector=None, loop=None, cookies=None,
if cookies is not None:
self._cookie_jar.update_cookies(cookies)

self._connector = connector
self._connector = connector # type: BaseConnector
self._connector_owner = connector_owner
self._default_auth = auth
self._version = version
Expand Down Expand Up @@ -216,7 +218,10 @@ def __del__(self, _warnings=warnings):
context['source_traceback'] = self._source_traceback
self._loop.call_exception_handler(context)

def request(self, method, url, **kwargs):
def request(self,
method: str,
url: StrOrURL,
**kwargs) -> '_RequestContextManager':
"""Perform HTTP request."""
return _RequestContextManager(self._request(method, url, **kwargs))

Expand Down Expand Up @@ -506,7 +511,7 @@ async def _request(self, method, url, *,
)
raise

def ws_connect(self, url, *,
def ws_connect(self, url: StrOrURL, *,
protocols=(),
timeout=10.0,
receive_timeout=None,
Expand Down Expand Up @@ -713,93 +718,99 @@ def _prepare_headers(self, headers):
added_names.add(key)
return result

def get(self, url, *, allow_redirects=True, **kwargs):
def get(self, url: StrOrURL, *, allow_redirects: bool=True,
**kwargs) -> '_RequestContextManager':
"""Perform HTTP GET request."""
return _RequestContextManager(
self._request(hdrs.METH_GET, url,
allow_redirects=allow_redirects,
**kwargs))

def options(self, url, *, allow_redirects=True, **kwargs):
def options(self, url: StrOrURL, *, allow_redirects: bool=True,
**kwargs) -> '_RequestContextManager':
"""Perform HTTP OPTIONS request."""
return _RequestContextManager(
self._request(hdrs.METH_OPTIONS, url,
allow_redirects=allow_redirects,
**kwargs))

def head(self, url, *, allow_redirects=False, **kwargs):
def head(self, url: StrOrURL, *, allow_redirects: bool=False,
**kwargs) -> '_RequestContextManager':
"""Perform HTTP HEAD request."""
return _RequestContextManager(
self._request(hdrs.METH_HEAD, url,
allow_redirects=allow_redirects,
**kwargs))

def post(self, url, *, data=None, **kwargs):
def post(self, url: StrOrURL,
*, data: Any=None, **kwargs) -> '_RequestContextManager':
"""Perform HTTP POST request."""
return _RequestContextManager(
self._request(hdrs.METH_POST, url,
data=data,
**kwargs))

def put(self, url, *, data=None, **kwargs):
def put(self, url: StrOrURL,
*, data: Any=None, **kwargs) -> '_RequestContextManager':
"""Perform HTTP PUT request."""
return _RequestContextManager(
self._request(hdrs.METH_PUT, url,
data=data,
**kwargs))

def patch(self, url, *, data=None, **kwargs):
def patch(self, url: StrOrURL,
*, data: Any=None, **kwargs) -> '_RequestContextManager':
"""Perform HTTP PATCH request."""
return _RequestContextManager(
self._request(hdrs.METH_PATCH, url,
data=data,
**kwargs))

def delete(self, url, **kwargs):
def delete(self, url: StrOrURL, **kwargs) -> '_RequestContextManager':
"""Perform HTTP DELETE request."""
return _RequestContextManager(
self._request(hdrs.METH_DELETE, url,
**kwargs))

async def close(self):
async def close(self) -> None:
"""Close underlying connector.
Release all acquired resources.
"""
if not self.closed:
if self._connector_owner:
if self._connector is not None and self._connector_owner:
self._connector.close()
self._connector = None

@property
def closed(self):
def closed(self) -> bool:
"""Is client session closed.
A readonly property.
"""
return self._connector is None or self._connector.closed

@property
def connector(self):
def connector(self) -> Optional[BaseConnector]:
"""Connector instance used for the session."""
return self._connector

@property
def cookie_jar(self):
def cookie_jar(self) -> CookieJar:
"""The session cookies."""
return self._cookie_jar

@property
def version(self):
def version(self) -> Tuple[int, int]:
"""The session HTTP protocol version."""
return self._version

@property
def loop(self):
def loop(self) -> asyncio.AbstractEventLoop:
"""Session's loop."""
return self._loop

def detach(self):
def detach(self) -> None:
"""Detach connector from session without closing the former.
Session is switched to closed state anyway.
Expand All @@ -813,14 +824,14 @@ def __exit__(self, exc_type, exc_val, exc_tb):
# __exit__ should exist in pair with __enter__ but never executed
pass # pragma: no cover

async def __aenter__(self):
async def __aenter__(self) -> 'ClientSession':
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()


class _BaseRequestContextManager(Coroutine):
class _BaseRequestContextManager(CoroutineABC):

__slots__ = ('_coro', '_resp')

Expand All @@ -836,14 +847,14 @@ def throw(self, arg):
def close(self):
return self._coro.close()

def __await__(self):
def __await__(self) -> Generator[Any, None, ClientResponse]:
ret = self._coro.__await__()
return ret

def __iter__(self):
return self.__await__()

async def __aenter__(self):
async def __aenter__(self) -> ClientResponse:
self._resp = await self._coro
return self._resp

Expand Down Expand Up @@ -872,7 +883,7 @@ def __init__(self, coro, session):
self._resp = None
self._session = session

async def __aenter__(self):
async def __aenter__(self) -> ClientResponse:
self._resp = await self._coro
return self._resp

Expand All @@ -899,7 +910,7 @@ def request(method, url, *,
loop=None,
read_until_eof=True,
proxy=None,
proxy_auth=None):
proxy_auth=None) -> _SessionRequestContextManager:
"""Constructs and sends a request. Returns response object.
method - HTTP method
url - request url
Expand Down
Loading

0 comments on commit 5d5bb46

Please sign in to comment.