|
| 1 | +# SPDX-FileCopyrightText: 2024 Heinz-Alexander Fütterer |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import logging |
| 8 | +from typing import TYPE_CHECKING, Literal, overload |
| 9 | + |
| 10 | +import httpx |
| 11 | + |
| 12 | +from re3data._client.base import BaseClient, Endpoint, ResourceType, ReturnType, is_valid_return_type |
| 13 | +from re3data._exceptions import RepositoryNotFoundError |
| 14 | +from re3data._response import Response, _build_response, _parse_repositories_response, _parse_repository_response |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from re3data._resources import Repository, RepositorySummary |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +async def async_log_response(response: httpx.Response) -> None: |
| 23 | + """Log the details of an HTTP response. |
| 24 | +
|
| 25 | + This function logs the HTTP method, URL, and status code of the response for debugging purposes. |
| 26 | + It uses the 'debug' logging level to provide detailed diagnostic information. |
| 27 | +
|
| 28 | + Args: |
| 29 | + response: The response object received from an HTTP request. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + None |
| 33 | + """ |
| 34 | + logger.debug( |
| 35 | + "[http] Response: %s %s - Status %s", response.request.method, response.request.url, response.status_code |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +@overload |
| 40 | +def _dispatch_return_type( |
| 41 | + response: Response, resource_type: Literal[ResourceType.REPOSITORY], return_type: ReturnType |
| 42 | +) -> Repository | Response | str: ... |
| 43 | +@overload |
| 44 | +def _dispatch_return_type( |
| 45 | + response: Response, resource_type: Literal[ResourceType.REPOSITORY_LIST], return_type: ReturnType |
| 46 | +) -> list[RepositorySummary] | Response | str: ... |
| 47 | + |
| 48 | + |
| 49 | +def _dispatch_return_type( |
| 50 | + response: Response, resource_type: ResourceType, return_type: ReturnType |
| 51 | +) -> Repository | list[RepositorySummary] | Response | str: |
| 52 | + """Dispatch the response to the correct return type based on the provided return type and resource type. |
| 53 | +
|
| 54 | + Args: |
| 55 | + response: The response object. |
| 56 | + resource_type: The type of resource being processed. |
| 57 | + return_type: The desired return type for the API resource. |
| 58 | +
|
| 59 | + Returns: |
| 60 | + Depending on the return_type and resource_type, this can be a Repository object, a list of RepositorySummary |
| 61 | + objects, an HTTP response, or the original XML. |
| 62 | + """ |
| 63 | + if return_type == ReturnType.DATACLASS: |
| 64 | + if resource_type == ResourceType.REPOSITORY_LIST: |
| 65 | + return _parse_repositories_response(response) |
| 66 | + if resource_type == ResourceType.REPOSITORY: |
| 67 | + return _parse_repository_response(response) |
| 68 | + if return_type == ReturnType.XML: |
| 69 | + return response.text |
| 70 | + return response |
| 71 | + |
| 72 | + |
| 73 | +class AsyncRepositoryManager: |
| 74 | + """A manager for interacting with repositories in the re3data API. |
| 75 | +
|
| 76 | + Attributes: |
| 77 | + _client: The client used to make requests. |
| 78 | + """ |
| 79 | + |
| 80 | + def __init__(self, client: AsyncClient) -> None: |
| 81 | + self._client = client |
| 82 | + |
| 83 | + async def list(self, return_type: ReturnType = ReturnType.DATACLASS) -> list[RepositorySummary] | Response | str: |
| 84 | + """List the metadata of all repositories in the re3data API. |
| 85 | +
|
| 86 | + Args: |
| 87 | + return_type: The desired return type for the API resource. Defaults to `ReturnType.DATACLASS`. |
| 88 | +
|
| 89 | + Returns: |
| 90 | + Depending on the `return_type`, this can be a list of RepositorySummary objects, an HTTP response, |
| 91 | + or the original XML. |
| 92 | +
|
| 93 | + Raises: |
| 94 | + ValueError: If an invalid `return_type` is provided. |
| 95 | + httpx.HTTPStatusError: If the server returned an error status code >= 500. |
| 96 | + """ |
| 97 | + is_valid_return_type(return_type) |
| 98 | + response = await self._client._request(Endpoint.REPOSITORY_LIST.value) |
| 99 | + return _dispatch_return_type(response, ResourceType.REPOSITORY_LIST, return_type) |
| 100 | + |
| 101 | + async def get( |
| 102 | + self, repository_id: str, return_type: ReturnType = ReturnType.DATACLASS |
| 103 | + ) -> Repository | Response | str: |
| 104 | + """Get the metadata of a specific repository. |
| 105 | +
|
| 106 | + Args: |
| 107 | + repository_id: The identifier of the repository to retrieve. |
| 108 | + return_type: The desired return type for the API resource. Defaults to `ReturnType.DATACLASS`. |
| 109 | +
|
| 110 | + Returns: |
| 111 | + Depending on the `return_type`, this can be a Repository object, an HTTP response, or the original XML. |
| 112 | +
|
| 113 | + Raises: |
| 114 | + ValueError: If an invalid `return_type` is provided. |
| 115 | + httpx.HTTPStatusError: If the server returned an error status code >= 500. |
| 116 | + RepositoryNotFoundError: If no repository with the given ID is found. |
| 117 | + """ |
| 118 | + is_valid_return_type(return_type) |
| 119 | + response = await self._client._request(Endpoint.REPOSITORY.value.format(repository_id=repository_id)) |
| 120 | + if response.status_code == httpx.codes.NOT_FOUND: |
| 121 | + raise RepositoryNotFoundError(f"No repository with id '{repository_id}' available at {response.url}.") |
| 122 | + return _dispatch_return_type(response, ResourceType.REPOSITORY, return_type) |
| 123 | + |
| 124 | + |
| 125 | +class AsyncClient(BaseClient): |
| 126 | + """A client that interacts with the re3data API. |
| 127 | +
|
| 128 | + Attributes: |
| 129 | + _client: The underlying HTTP client. |
| 130 | + _repository_manager: The repository manager to retrieve metadata from the repositories endpoints. |
| 131 | +
|
| 132 | + Examples: |
| 133 | + >>> async_client = AsyncClient(): |
| 134 | + >>> response = await async_client.repositories.list() |
| 135 | + >>> response |
| 136 | + [RepositorySummary(id='r3d100010468', doi='https://doi.org/10.17616/R3QP53', name='Zenodo', link=Link(href='https://www.re3data.org/api/beta/repository/r3d100010468', rel='self'))] |
| 137 | + ... (remaining repositories truncated) |
| 138 | + """ |
| 139 | + |
| 140 | + _client: httpx.AsyncClient |
| 141 | + |
| 142 | + def __init__(self) -> None: |
| 143 | + super().__init__(httpx.AsyncClient) |
| 144 | + self._client.event_hooks["response"] = [async_log_response] |
| 145 | + self._repository_manager: AsyncRepositoryManager = AsyncRepositoryManager(self) |
| 146 | + |
| 147 | + async def _request(self, path: str) -> Response: |
| 148 | + """Send a HTTP GET request to the specified API endpoint. |
| 149 | +
|
| 150 | + Args: |
| 151 | + path: The path to send the request to. |
| 152 | +
|
| 153 | + Returns: |
| 154 | + The response object from the HTTP request. |
| 155 | +
|
| 156 | + Raises: |
| 157 | + httpx.HTTPStatusError: If the server returned an error status code >= 500. |
| 158 | + RepositoryNotFoundError: If the `repository_id` is not found. |
| 159 | + """ |
| 160 | + http_response = await self._client.get(path) |
| 161 | + if http_response.is_server_error: |
| 162 | + http_response.raise_for_status() |
| 163 | + return _build_response(http_response) |
| 164 | + |
| 165 | + @property |
| 166 | + def repositories(self) -> AsyncRepositoryManager: |
| 167 | + """Get the repository manager for this client. |
| 168 | +
|
| 169 | + Returns: |
| 170 | + The repository manager. |
| 171 | + """ |
| 172 | + return self._repository_manager |
0 commit comments