Skip to content
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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ jobs:
- name: ruff
run: ruff check src tests examples
- name: mypy
run: mypy src tests/fake_pusher.py
run: mypy src tests/fake_pusher.py tests/test_request_files.py

test:
name: tests (Python ${{ matrix.python-version }})
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "deapi-sdk"
version = "0.5.1"
version = "0.5.2"
description = "Official Python SDK for DeAPI — distributed AI inference platform"
readme = "README.md"
license = "MIT"
Expand Down
24 changes: 19 additions & 5 deletions src/deapi_sdk/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import asyncio
import math
import time
from collections.abc import Mapping, Sequence
from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from typing import Any
from typing import IO, Any, TypeAlias

import httpx

Expand All @@ -30,6 +31,19 @@
ValidationError,
)

# Multipart file parts accepted by the low-level ``request()`` / ``post()``, mirroring what httpx
# accepts (a mapping or a sequence of (field, part) pairs; content as bytes or a binary file object,
# optionally with a filename, content type and headers). Resource methods build these from
# ``FileInput`` via ``normalize_file``; a plain ``str`` is deliberately not allowed as content.
FileContent: TypeAlias = IO[bytes] | bytes
FilePart: TypeAlias = (
FileContent
| tuple[str | None, FileContent]
| tuple[str | None, FileContent, str | None]
| tuple[str | None, FileContent, str | None, Mapping[str, str]]
)
RequestFiles: TypeAlias = Mapping[str, FilePart] | Sequence[tuple[str, FilePart]]


class BaseClient:
"""Shared logic for sync and async HTTP clients."""
Expand Down Expand Up @@ -246,7 +260,7 @@ def request(
*,
json: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
files: list[tuple[str, tuple[str, bytes, str]]] | None = None,
files: RequestFiles | None = None,
params: dict[str, Any] | None = None,
) -> Any:
last_exc: Exception | None = None
Expand Down Expand Up @@ -290,7 +304,7 @@ def post(
*,
json: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
files: list[tuple[str, tuple[str, bytes, str]]] | None = None,
files: RequestFiles | None = None,
) -> Any:
return self.request("POST", url, json=json, data=data, files=files)

Expand Down Expand Up @@ -342,7 +356,7 @@ async def request(
*,
json: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
files: list[tuple[str, tuple[str, bytes, str]]] | None = None,
files: RequestFiles | None = None,
params: dict[str, Any] | None = None,
) -> Any:
last_exc: Exception | None = None
Expand Down Expand Up @@ -386,7 +400,7 @@ async def post(
*,
json: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
files: list[tuple[str, tuple[str, bytes, str]]] | None = None,
files: RequestFiles | None = None,
) -> Any:
return await self.request("POST", url, json=json, data=data, files=files)

Expand Down
2 changes: 1 addition & 1 deletion src/deapi_sdk/_version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from __future__ import annotations

__version__ = "0.5.1"
__version__ = "0.5.2"
61 changes: 61 additions & 0 deletions tests/test_request_files.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Low-level ``request()`` / ``post()`` accept every multipart ``files`` shape httpx does.

This module is also type-checked with mypy --strict in CI, so the calls below double as a typing test
for ``deapi_sdk._client.RequestFiles``.
"""

from __future__ import annotations

import io

import httpx
import respx

from deapi_sdk import AsyncDeapiClient, DeapiClient
from deapi_sdk._client import RequestFiles
from tests.conftest import TEST_API_KEY, TEST_BASE_URL

URL = f"{TEST_BASE_URL}/api/v2/images/upscales"
OK = httpx.Response(200, json={"data": {"request_id": "req-1"}})


def _parts() -> list[RequestFiles]:
return [
{"image": ("a.png", io.BytesIO(b"PNGDATA-1"), "image/png")},
[("image", ("a.png", io.BytesIO(b"PNGDATA-1"), "image/png"))],
[("image", ("a.png", b"PNGDATA-1", "image/png"))],
{"image": io.BytesIO(b"PNGDATA-1")},
]


class TestRequestFilesShapes:
@respx.mock
def test_sync_post_accepts_mapping_and_sequence_with_file_objects(self) -> None:
route = respx.post(URL).mock(return_value=OK)
with DeapiClient(api_key=TEST_API_KEY, base_url=TEST_BASE_URL, fill_model_defaults=False) as client:
for files in _parts():
client._http_client.post(URL, data={"model": "m"}, files=files)
assert b"PNGDATA-1" in route.calls.last.request.content
assert route.call_count == 4

@respx.mock
async def test_async_post_accepts_mapping_and_sequence_with_file_objects(self) -> None:
route = respx.post(URL).mock(return_value=OK)
async with AsyncDeapiClient(api_key=TEST_API_KEY, base_url=TEST_BASE_URL, fill_model_defaults=False) as client:
for files in _parts():
await client._http_client.post(URL, data={"model": "m"}, files=files)
assert b"PNGDATA-1" in route.calls.last.request.content
assert route.call_count == 4

@respx.mock
def test_rate_limited_resend_sends_the_whole_file_again(self) -> None:
route = respx.post(URL).mock(
side_effect=[httpx.Response(429, headers={"Retry-After": "1"}, json={"message": "slow down"}), OK]
)
with DeapiClient(
api_key=TEST_API_KEY, base_url=TEST_BASE_URL, fill_model_defaults=False, max_retry_after=0.01
) as client:
files: RequestFiles = {"image": ("a.png", io.BytesIO(b"PNGDATA-RETRY"), "image/png")}
client._http_client.post(URL, data={"model": "m"}, files=files)
assert route.call_count == 2
assert all(b"PNGDATA-RETRY" in call.request.content for call in route.calls)