Repository navigation
refactor: extract requests transport #469
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
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6c77ae6
feat: use UnleashEngine.get_spec_version
alexanto 3cc3037
chore: remove unused function and dep
alexanto d9fb8e5
refactor: add url validation in init
alexanto b4a2d6d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9d39224
refactor: add url validation in init
alexanto de6e361
refactor: rename transport to apiclient
alexanto 1abab9a
refactor: default transport
alexanto 73b33e8
Merge branch 'main' into refactor/extract-requests-transport
alexanto 653538f
refactor: make request method an enum
alexanto 1ede617
refactor: execute docstring
alexanto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| """ | ||
| HTTP layer under the Unleash API client: sends one request and returns the | ||
| response. | ||
| """ | ||
|
|
||
| from dataclasses import dataclass, field | ||
| from enum import Enum | ||
| from typing import Any, Mapping, Optional, Protocol, runtime_checkable | ||
|
|
||
| import requests | ||
| from requests.adapters import HTTPAdapter | ||
| from urllib3 import Retry | ||
|
|
||
| from UnleashClient.constants import REQUEST_TIMEOUT | ||
|
|
||
|
|
||
| class Method(str, Enum): | ||
| GET = "GET" | ||
| POST = "POST" | ||
|
|
||
| __str__ = str.__str__ | ||
|
|
||
|
|
||
| @dataclass(frozen=True, kw_only=True) | ||
| class Request: | ||
| """ | ||
| HTTP request. | ||
|
|
||
| :param method: HTTP method. | ||
| :param url: Absolute url, without the query string. | ||
| :param headers: Headers to send. | ||
| :param params: Query string parameters. | ||
| :param body: Request body, or None to send none. | ||
| """ | ||
|
|
||
| method: Method | ||
| url: str | ||
| headers: Mapping[str, str] | ||
| params: Mapping[str, str] = field(default_factory=dict) | ||
| body: Optional[bytes] = None | ||
|
|
||
|
|
||
| @dataclass(frozen=True, kw_only=True) | ||
| class Response: | ||
| """ | ||
| HTTP response. Every status is a response, not an error: deciding what | ||
| a status means is the API client's job. | ||
|
|
||
| :param status: HTTP status code. | ||
| :param headers: Response headers, looked up case-insensitively. | ||
| :param body: Raw response body. | ||
| """ | ||
|
|
||
| status: int | ||
| headers: Mapping[str, str] | ||
| body: bytes | ||
|
|
||
|
|
||
| @runtime_checkable | ||
| class Transport(Protocol): | ||
| """Sends requests for the sync client.""" | ||
|
|
||
| def execute(self, request: Request) -> Response: | ||
| """ | ||
| Implementations must send ``request`` once and return the response, | ||
| regardless of its status code. | ||
|
|
||
| Implementations must not raise when a response was received, even for | ||
| an error status. They raise only if no response was received, for | ||
| example due to a connection error or timeout. | ||
| """ | ||
|
alexanto marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| class RequestsTransport: | ||
| """ | ||
| Sends requests with ``requests``, on a fresh session for every request. | ||
|
|
||
| :param timeout: Seconds to wait for the connection and for each read. | ||
| :param _retries: GET requests are retried this many times on a connection | ||
| error or a 500, 502 or 504, by urllib3. | ||
| :param _request_kwargs: extra keyword arguments for every ``requests`` call. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| timeout: float = REQUEST_TIMEOUT, | ||
| # these two are are going away too | ||
| _retries: Optional[int] = None, | ||
| _request_kwargs: Optional[Mapping[str, Any]] = None, | ||
| ) -> None: | ||
| self._timeout = timeout | ||
| self._retries = _retries | ||
| self._request_kwargs = dict(_request_kwargs or {}) | ||
|
|
||
| def execute(self, request: Request) -> Response: | ||
| kwargs: dict = {"headers": dict(request.headers), "timeout": self._timeout} | ||
| if request.params: | ||
| kwargs["params"] = dict(request.params) | ||
| if request.body is not None: | ||
| kwargs["data"] = request.body | ||
|
|
||
| with requests.Session() as session: | ||
| if request.method == Method.GET and self._retries is not None: | ||
| adapter = HTTPAdapter( | ||
| max_retries=Retry( | ||
| total=self._retries, status_forcelist=[500, 502, 504] | ||
|
alexanto marked this conversation as resolved.
Resolved
|
||
| ) | ||
| ) | ||
| session.mount("https://", adapter) | ||
| session.mount("http://", adapter) | ||
|
|
||
| resp = session.request( | ||
| request.method, request.url, **kwargs, **self._request_kwargs | ||
| ) | ||
| return Response( | ||
| status=resp.status_code, headers=resp.headers, body=resp.content | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.