Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Add Parameter httpx_kwargs to HTTPXRequest #4451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions telegram/request/_httpxrequest.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains methods to make POST and GET requests using the httpx library."""
from typing import Collection, Optional, Tuple, Union
from typing import Any, Collection, Dict, Optional, Tuple, Union

import httpx

Expand Down Expand Up @@ -122,6 +122,20 @@ class HTTPXRequest(BaseRequest):
:meth:`do_request`. Defaults to ``20`` seconds.

.. versionadded:: 21.0
httpx_kwargs (Dict[:obj:`str`, Any], optional): Additional keyword arguments to be passed
to the `httpx.AsyncClient <https://www.python-httpx.org/api/#asyncclient>`_
constructor.

Warning:
This parameter is intended for advanced users that want to fine-tune the behavior
of the underlying ``httpx`` client. The values passed here will override all the
defaults set by ``python-telegram-bot`` and all other parameters passed to
:class:`HTTPXRequest`. The only exception is the :paramref:`media_write_timeout`
parameter, which is not passed to the client constructor.
No runtime warnings will be issued about parameters that are overridden in this
way.

.. versionadded:: NEXT.VERSION

"""

Expand All @@ -139,6 +153,7 @@ def __init__(
socket_options: Optional[Collection[SocketOpt]] = None,
proxy: Optional[Union[str, httpx.Proxy, httpx.URL]] = None,
media_write_timeout: Optional[float] = 20.0,
httpx_kwargs: Optional[Dict[str, Any]] = None,
):
if proxy_url is not None and proxy is not None:
raise ValueError("The parameters `proxy_url` and `proxy` are mutually exclusive.")
Expand Down Expand Up @@ -183,6 +198,7 @@ def __init__(
"limits": limits,
"transport": transport,
**http_kwargs,
**(httpx_kwargs or {}),
}

try:
Expand Down Expand Up @@ -221,7 +237,7 @@ def read_timeout(self) -> Optional[float]:
return self._client.timeout.read

def _build_client(self) -> httpx.AsyncClient:
return httpx.AsyncClient(**self._client_kwargs) # type: ignore[arg-type]
return httpx.AsyncClient(**self._client_kwargs)

async def initialize(self) -> None:
"""See :meth:`BaseRequest.initialize`."""
Expand Down
2 changes: 1 addition & 1 deletion tests/ext/test_applicationbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def test_all_methods_request(self, builder, get_updates):
arguments = inspect.signature(HTTPXRequest.__init__).parameters.keys()
prefix = "get_updates_" if get_updates else ""
for argument in arguments:
if argument == "self":
if argument in ("self", "httpx_kwargs"):
continue
if argument == "media_write_timeout" and get_updates:
# get_updates never makes media requests
Expand Down
31 changes: 31 additions & 0 deletions tests/request/test_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,37 @@ def test_slot_behaviour(self):
assert getattr(inst, at, "err") != "err", f"got extra slot '{at}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"

def test_httpx_kwargs(self, monkeypatch):
self.test_flag = {}

orig_init = httpx.AsyncClient.__init__

class Client(httpx.AsyncClient):
def __init__(*args, **kwargs):
orig_init(*args, **kwargs)
self.test_flag["args"] = args
self.test_flag["kwargs"] = kwargs

monkeypatch.setattr(httpx, "AsyncClient", Client)

HTTPXRequest(
connect_timeout=1,
connection_pool_size=42,
http_version="2",
httpx_kwargs={
"timeout": httpx.Timeout(7),
"limits": httpx.Limits(max_connections=7),
"http1": True,
"verify": False,
},
)
kwargs = self.test_flag["kwargs"]

assert kwargs["timeout"].connect == 7
assert kwargs["limits"].max_connections == 7
assert kwargs["http1"] is True
assert kwargs["verify"] is False

async def test_context_manager(self, monkeypatch):
async def initialize():
self.test_flag = ["initialize"]
Expand Down
Loading