Skip to content

Commit efa7a7b

Browse files
💥 ♻️ drop requests in favor of httpx (#414)
1 parent 2ebb009 commit efa7a7b

18 files changed

Lines changed: 134 additions & 136 deletions

‎.pre-commit-config.yaml‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,7 @@ repos:
3535
args: []
3636
exclude: "tests/|examples/|docs/"
3737
additional_dependencies:
38-
- toml
39-
- types-requests
38+
- httpx
4039
- types-setuptools
4140
- importlib-metadata
4241
- types-Pillow

‎mindee/image/extracted_image.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,11 +64,11 @@ def save_to_file(self, output_path: Path | str, file_format: str | None = None):
6464
else:
6565
image.save(resolved_path)
6666
logger.info("File saved successfully to '%s'.", resolved_path)
67-
except TypeError as exc:
68-
raise MindeeError("Invalid path/filename provided.") from exc
69-
except Exception as exc:
70-
print(exc)
71-
raise MindeeError(f"Could not save file {Path(output_path).name}.") from exc
67+
except TypeError as e:
68+
raise MindeeError("Invalid path/filename provided.") from e
69+
except Exception as e:
70+
print(e)
71+
raise MindeeError(f"Could not save file {Path(output_path).name}.") from e
7272

7373
def as_input_source(self) -> FileInput:
7474
"""

‎mindee/input/local_input_source.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@ def __init__(self) -> None:
4848
try:
4949
pdf = pdfium.PdfDocument(self.file_object)
5050
self.page_count = len(pdf)
51-
except pdfium.PdfiumError as exc:
51+
except pdfium.PdfiumError as e:
5252
logger.warning(
53-
"Could not open PDF file: %s due to %s", self.filename, exc
53+
"Could not open PDF file: %s due to %s", self.filename, e
5454
)
5555
self.page_count = 0
5656
self.file_object.seek(0)
@@ -106,11 +106,11 @@ def fix_pdf(self, maximum_offset: int = 500) -> None:
106106
f"PDF couldn't be fixed. PDF tag was found at position {pos}."
107107
)
108108
self.file_mimetype = "application/pdf"
109-
except MimeTypeError as exc:
110-
raise exc
111-
except Exception as exc:
112-
print(f"Attempt to fix pdf raised exception {exc}.")
113-
raise exc
109+
except MimeTypeError as e:
110+
raise e
111+
except Exception as e:
112+
logger.error("Attempt to fix pdf raised exception %s.", e)
113+
raise e
114114

115115
def is_pdf(self) -> bool:
116116
""":return: True if the file is a PDF."""

‎mindee/input/local_response.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ def as_dict(self) -> dict[str, Any]:
5353
try:
5454
self._file.seek(0)
5555
out_json = json.loads(self._file.read())
56-
except json.decoder.JSONDecodeError as exc:
57-
raise MindeeError("File is not a valid dictionary.") from exc
56+
except json.decoder.JSONDecodeError as e:
57+
raise MindeeError("File is not a valid dictionary.") from e
5858
return out_json
5959

6060
@staticmethod
@@ -87,8 +87,8 @@ def get_hmac_signature(self, secret_key: str | bytes | bytearray):
8787
self._file.read(),
8888
algorithm,
8989
)
90-
except (TypeError, ValueError) as exc:
91-
raise MindeeError("Could not get HMAC signature from payload.") from exc
90+
except (TypeError, ValueError) as e:
91+
raise MindeeError("Could not get HMAC signature from payload.") from e
9292

9393
return mac.hexdigest()
9494

@@ -114,5 +114,5 @@ def deserialize_response(self, response_class: type[ResponseT]) -> ResponseT:
114114
"""
115115
try:
116116
return response_class(self.as_dict)
117-
except KeyError as exc:
118-
raise MindeeError("Invalid class specified for deserialization.") from exc
117+
except KeyError as e:
118+
raise MindeeError("Invalid class specified for deserialization.") from e

‎mindee/input/url_input_source.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from pathlib import Path
66
from urllib.parse import urlparse
77

8-
import requests
8+
import httpx
99

1010
from mindee.error.mindee_error import MindeeSourceError
1111
from mindee.input.bytes_input import BytesInput
@@ -153,7 +153,7 @@ def __get_file_extension(filename) -> str | None:
153153
:return: The lowercase file extension or None if not found.
154154
"""
155155
ext = os.path.splitext(filename)[1]
156-
return ext.lower() if ext else None
156+
return str(ext).lower() if ext else None
157157

158158
def __fill_filename(self, filename=None) -> str:
159159
"""
@@ -167,7 +167,7 @@ def __fill_filename(self, filename=None) -> str:
167167

168168
if not filename or not os.path.splitext(filename)[1]:
169169
filename = self.__generate_file_name(
170-
extension=URLInputSource.__get_file_extension(filename)
170+
extension=URLInputSource.__get_file_extension(filename) or ""
171171
)
172172

173173
return filename
@@ -185,15 +185,15 @@ def __make_request(url, auth, headers, redirects, max_redirects) -> bytes:
185185
:return: The content of the response.
186186
:raises MindeeSourceError: If max redirects are exceeded or the request fails.
187187
"""
188-
result = requests.get(url, headers=headers, timeout=120, auth=auth)
188+
result = httpx.get(url, headers=headers, timeout=120, auth=auth)
189189
if 299 < result.status_code < 400:
190190
if redirects == max_redirects:
191191
raise MindeeSourceError(
192192
f"Can't reach URL after {redirects} out of {max_redirects} redirects, "
193193
f"aborting operation."
194194
)
195195
return URLInputSource.__make_request(
196-
redirects.location, auth, headers, redirects + 1, max_redirects
196+
result.headers["Location"], auth, headers, redirects + 1, max_redirects
197197
)
198198

199199
if result.status_code >= 400 or result.status_code < 200:

‎mindee/mindee_http/response_validation.py‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,34 @@
11
import json
22

3-
import requests
3+
import httpx
44

55
from mindee.parsing.common import StringDict
66

77

8-
def is_valid_sync_response(response: requests.Response) -> bool:
8+
def is_valid_sync_response(response: httpx.Response) -> bool:
99
"""
1010
Checks if the synchronous response is valid. Returns True if the response is valid.
1111
1212
:param response: a requests response object.
1313
:return: bool
1414
"""
15-
if not response or not response.ok:
15+
if not response or response.is_error:
16+
return False
17+
try:
18+
response_json = response.json()
19+
except httpx.DecodingError:
1620
return False
17-
response_json = json.loads(response.content)
1821
# EXTREMELY rare edge case where raw html is sent instead of json.
1922
return isinstance(response_json, dict)
2023

2124

22-
def is_valid_async_response(response: requests.Response) -> bool:
25+
def is_valid_async_response(response: httpx.Response) -> bool:
2326
"""
2427
Checks if the asynchronous response is valid. Also checks if it is a valid synchronous response.
2528
2629
Returns True if the response is valid.
2730
28-
:param response: a requests response object.
31+
:param response: an httpx response object.
2932
:return: bool
3033
"""
3134
if not is_valid_sync_response(response):
@@ -43,15 +46,15 @@ def is_valid_async_response(response: requests.Response) -> bool:
4346
return False
4447

4548

46-
def clean_request_json(response: requests.Response) -> StringDict:
49+
def clean_request_json(response: httpx.Response) -> StringDict:
4750
"""
4851
Checks and correct the response error format depending on the two possible kind of returns.
4952
5053
:param response: Raw request response.
5154
:return: Returns the job error if the error is due to parsing, returns the http error otherwise.
5255
"""
5356
response_json = response.json()
54-
if response.status_code < 200 or response.status_code > 302:
57+
if response.is_error:
5558
response_json["status_code"] = response.status_code
5659
return response_json
5760
corrected_json = response_json

‎mindee/pdf/extracted_pdf.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ def get_page_count(self) -> int:
2222
try:
2323
pdf = pdfium.PdfDocument(self.pdf_bytes)
2424
return len(pdf)
25-
except Exception as exc:
25+
except Exception as e:
2626
raise MindeeError(
2727
"Could not retrieve page count from Extracted PDF object."
28-
) from exc
28+
) from e
2929

3030
def save_to_file(self, output_path: Path | str):
3131
"""

‎mindee/v1/client.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,8 +225,8 @@ def load_prediction(
225225
if local_response.as_dict.get("job"):
226226
return AsyncPredictResponse(product_class, local_response.as_dict)
227227
return PredictResponse(product_class, local_response.as_dict)
228-
except KeyError as exc:
229-
raise MindeeError("No prediction found in local response.") from exc
228+
except KeyError as e:
229+
raise MindeeError("No prediction found in local response.") from e
230230

231231
def parse_queued(
232232
self,

0 commit comments

Comments
 (0)