Skip to content

Commit

Permalink
[PR #10300/3d06cc1][3.12] Use kwargs in aiohttp.client.request (#10302)
Browse files Browse the repository at this point in the history
(cherry picked from commit 3d06cc1)
  • Loading branch information
Cycloctane authored Jan 6, 2025
1 parent d5dd9d0 commit 52e4ea6
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 102 deletions.
2 changes: 2 additions & 0 deletions CHANGES/10300.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Update :py:func:`~aiohttp.request` to make it accept ``_RequestOptions`` kwargs.
-- by :user:`Cycloctane`.
178 changes: 76 additions & 102 deletions aiohttp/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1469,106 +1469,80 @@ async def __aexit__(
await self._session.close()


def request(
method: str,
url: StrOrURL,
*,
params: Query = None,
data: Any = None,
json: Any = None,
headers: Optional[LooseHeaders] = None,
skip_auto_headers: Optional[Iterable[str]] = None,
auth: Optional[BasicAuth] = None,
allow_redirects: bool = True,
max_redirects: int = 10,
compress: Optional[str] = None,
chunked: Optional[bool] = None,
expect100: bool = False,
raise_for_status: Optional[bool] = None,
read_until_eof: bool = True,
proxy: Optional[StrOrURL] = None,
proxy_auth: Optional[BasicAuth] = None,
timeout: Union[ClientTimeout, object] = sentinel,
cookies: Optional[LooseCookies] = None,
version: HttpVersion = http.HttpVersion11,
connector: Optional[BaseConnector] = None,
read_bufsize: Optional[int] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
max_line_size: int = 8190,
max_field_size: int = 8190,
) -> _SessionRequestContextManager:
"""Constructs and sends a request.
Returns response object.
method - HTTP method
url - request url
params - (optional) Dictionary or bytes to be sent in the query
string of the new request
data - (optional) Dictionary, bytes, or file-like object to
send in the body of the request
json - (optional) Any json compatible python object
headers - (optional) Dictionary of HTTP Headers to send with
the request
cookies - (optional) Dict object to send with the request
auth - (optional) BasicAuth named tuple represent HTTP Basic Auth
auth - aiohttp.helpers.BasicAuth
allow_redirects - (optional) If set to False, do not follow
redirects
version - Request HTTP version.
compress - Set to True if request has to be compressed
with deflate encoding.
chunked - Set to chunk size for chunked transfer encoding.
expect100 - Expect 100-continue response from server.
connector - BaseConnector sub-class instance to support
connection pooling.
read_until_eof - Read response until eof if response
does not have Content-Length header.
loop - Optional event loop.
timeout - Optional ClientTimeout settings structure, 5min
total timeout by default.
Usage::
>>> import aiohttp
>>> resp = await aiohttp.request('GET', 'http://python.org/')
>>> resp
<ClientResponse(python.org/) [200]>
>>> data = await resp.read()
"""
connector_owner = False
if connector is None:
connector_owner = True
connector = TCPConnector(loop=loop, force_close=True)

session = ClientSession(
loop=loop,
cookies=cookies,
version=version,
timeout=timeout,
connector=connector,
connector_owner=connector_owner,
)
if sys.version_info >= (3, 11) and TYPE_CHECKING:

return _SessionRequestContextManager(
session._request(
method,
url,
params=params,
data=data,
json=json,
headers=headers,
skip_auto_headers=skip_auto_headers,
auth=auth,
allow_redirects=allow_redirects,
max_redirects=max_redirects,
compress=compress,
chunked=chunked,
expect100=expect100,
raise_for_status=raise_for_status,
read_until_eof=read_until_eof,
proxy=proxy,
proxy_auth=proxy_auth,
read_bufsize=read_bufsize,
max_line_size=max_line_size,
max_field_size=max_field_size,
),
session,
)
def request(
method: str,
url: StrOrURL,
*,
version: HttpVersion = http.HttpVersion11,
connector: Optional[BaseConnector] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Unpack[_RequestOptions],
) -> _SessionRequestContextManager: ...

else:

def request(
method: str,
url: StrOrURL,
*,
version: HttpVersion = http.HttpVersion11,
connector: Optional[BaseConnector] = None,
loop: Optional[asyncio.AbstractEventLoop] = None,
**kwargs: Any,
) -> _SessionRequestContextManager:
"""Constructs and sends a request.
Returns response object.
method - HTTP method
url - request url
params - (optional) Dictionary or bytes to be sent in the query
string of the new request
data - (optional) Dictionary, bytes, or file-like object to
send in the body of the request
json - (optional) Any json compatible python object
headers - (optional) Dictionary of HTTP Headers to send with
the request
cookies - (optional) Dict object to send with the request
auth - (optional) BasicAuth named tuple represent HTTP Basic Auth
auth - aiohttp.helpers.BasicAuth
allow_redirects - (optional) If set to False, do not follow
redirects
version - Request HTTP version.
compress - Set to True if request has to be compressed
with deflate encoding.
chunked - Set to chunk size for chunked transfer encoding.
expect100 - Expect 100-continue response from server.
connector - BaseConnector sub-class instance to support
connection pooling.
read_until_eof - Read response until eof if response
does not have Content-Length header.
loop - Optional event loop.
timeout - Optional ClientTimeout settings structure, 5min
total timeout by default.
Usage::
>>> import aiohttp
>>> async with aiohttp.request('GET', 'http://python.org/') as resp:
... print(resp)
... data = await resp.read()
<ClientResponse(https://www.python.org/) [200 OK]>
"""
connector_owner = False
if connector is None:
connector_owner = True
connector = TCPConnector(loop=loop, force_close=True)

session = ClientSession(
loop=loop,
cookies=kwargs.pop("cookies", None),
version=version,
timeout=kwargs.pop("timeout", sentinel),
connector=connector,
connector_owner=connector_owner,
)

return _SessionRequestContextManager(
session._request(method, url, **kwargs),
session,
)
2 changes: 2 additions & 0 deletions docs/spelling_wordlist.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ app
app’s
apps
arg
args
Arsenic
async
asyncio
Expand Down Expand Up @@ -169,6 +170,7 @@ keepaliving
kib
KiB
kwarg
kwargs
latin
lifecycle
linux
Expand Down
16 changes: 16 additions & 0 deletions tests/test_client_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -3382,6 +3382,22 @@ async def handler(request: web.Request) -> web.Response:
await server.close()


async def test_aiohttp_request_ssl(
aiohttp_server: AiohttpServer,
ssl_ctx: ssl.SSLContext,
client_ssl_ctx: ssl.SSLContext,
) -> None:
async def handler(request: web.Request) -> web.Response:
return web.Response()

app = web.Application()
app.router.add_get("/", handler)
server = await aiohttp_server(app, ssl=ssl_ctx)

async with aiohttp.request("GET", server.make_url("/"), ssl=client_ssl_ctx) as resp:
assert resp.status == 200


async def test_yield_from_in_session_request(aiohttp_client: AiohttpClient) -> None:
# a test for backward compatibility with yield from syntax
async def handler(request):
Expand Down

0 comments on commit 52e4ea6

Please sign in to comment.