|
| 1 | +# Copyright 2025 EPAM Systems |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License |
| 14 | + |
| 15 | +"""This module designed to help with synchronous HTTP request/response handling.""" |
| 16 | + |
| 17 | +from types import TracebackType |
| 18 | +from typing import Any, Callable, Optional, Type, Union |
| 19 | + |
| 20 | +import requests |
| 21 | + |
| 22 | +from reportportal_client._internal.services.auth import Auth |
| 23 | + |
| 24 | +AUTH_PROBLEM_STATUSES: set = {401, 403} |
| 25 | + |
| 26 | + |
| 27 | +class ClientSession: |
| 28 | + """Class wraps requests.Session and adds authentication support.""" |
| 29 | + |
| 30 | + _client: requests.Session |
| 31 | + __auth: Optional[Auth] |
| 32 | + |
| 33 | + def __init__( |
| 34 | + self, |
| 35 | + auth: Optional[Auth] = None, |
| 36 | + ): |
| 37 | + """Initialize an instance of the session with arguments. |
| 38 | +
|
| 39 | + :param auth: authentication instance to use for requests |
| 40 | + """ |
| 41 | + self._client = requests.Session() |
| 42 | + self.__auth = auth |
| 43 | + |
| 44 | + def __request(self, method: Callable, url: Union[str, bytes], **kwargs: Any) -> requests.Response: |
| 45 | + """Make a request with authentication support. |
| 46 | +
|
| 47 | + The method adds Authorization header if auth is configured and handles auth refresh |
| 48 | + on 401/403 responses. |
| 49 | + """ |
| 50 | + # Clone kwargs and add Authorization header if auth is configured |
| 51 | + request_kwargs = kwargs.copy() |
| 52 | + if self.__auth: |
| 53 | + auth_header = self.__auth.get() |
| 54 | + if auth_header: |
| 55 | + if "headers" not in request_kwargs: |
| 56 | + request_kwargs["headers"] = {} |
| 57 | + else: |
| 58 | + request_kwargs["headers"] = request_kwargs["headers"].copy() |
| 59 | + request_kwargs["headers"]["Authorization"] = auth_header |
| 60 | + |
| 61 | + result = method(url, **request_kwargs) |
| 62 | + |
| 63 | + # Check for authentication errors |
| 64 | + if result.status_code in AUTH_PROBLEM_STATUSES and self.__auth: |
| 65 | + refreshed_header = self.__auth.refresh() |
| 66 | + if refreshed_header: |
| 67 | + # Retry with new auth header |
| 68 | + request_kwargs["headers"] = request_kwargs.get("headers", {}).copy() |
| 69 | + request_kwargs["headers"]["Authorization"] = refreshed_header |
| 70 | + result = method(url, **request_kwargs) |
| 71 | + |
| 72 | + return result |
| 73 | + |
| 74 | + def get(self, url: str, **kwargs: Any) -> requests.Response: |
| 75 | + """Perform HTTP GET request.""" |
| 76 | + return self.__request(self._client.get, url, **kwargs) |
| 77 | + |
| 78 | + def post(self, url: str, **kwargs: Any) -> requests.Response: |
| 79 | + """Perform HTTP POST request.""" |
| 80 | + return self.__request(self._client.post, url, **kwargs) |
| 81 | + |
| 82 | + def put(self, url: str, **kwargs: Any) -> requests.Response: |
| 83 | + """Perform HTTP PUT request.""" |
| 84 | + return self.__request(self._client.put, url, **kwargs) |
| 85 | + |
| 86 | + def mount(self, prefix: str, adapter: requests.adapters.BaseAdapter) -> None: |
| 87 | + """Mount an adapter to a specific URL prefix. |
| 88 | +
|
| 89 | + :param prefix: URL prefix (e.g., 'http://', 'https://') |
| 90 | + :param adapter: Adapter instance to mount |
| 91 | + """ |
| 92 | + self._client.mount(prefix, adapter) |
| 93 | + |
| 94 | + def close(self) -> None: |
| 95 | + """Gracefully close internal requests.Session class instance.""" |
| 96 | + self._client.close() |
| 97 | + |
| 98 | + def __enter__(self) -> "ClientSession": |
| 99 | + """Auxiliary method which controls what `with` construction does on block enter.""" |
| 100 | + return self |
| 101 | + |
| 102 | + def __exit__( |
| 103 | + self, |
| 104 | + exc_type: Optional[Type[BaseException]], |
| 105 | + exc_val: Optional[BaseException], |
| 106 | + exc_tb: Optional[TracebackType], |
| 107 | + ) -> None: |
| 108 | + """Auxiliary method which controls what `with` construction does on block exit.""" |
| 109 | + self.close() |
0 commit comments