Skip to main content

opengater-storage-client

Тонкий async-клиент к сервису opengater-storage — инкапсулирует POST /uploads (получение presigned-PUT URL) и DELETE /objects (удаление файла). Аутентификация через заголовок X-API-Key.

По структуре аналогичен opengater-globalauth-client: без FastAPI, без брокера, только httpx + pydantic.


Установка

После публикации на PyPI:

uv add opengater-storage-client

На время разработки — git-зависимость на тег:

uv add "opengater-storage-client @ git+https://gitlab.com/toltol1992toltol/opengater-storage-client.git@v0.1.0"

Быстрый старт

from opengater_storage_client import StorageClient

storage = StorageClient(base_url="http://opengater-storage:8000", api_key="...")

# Создать загрузку — получить presigned-PUT URL
res = await storage.create_upload("image/png", prefix="news/articles")
# res.upload_url — PUT сюда файл напрямую из браузера/клиента
# res.key        — ключ объекта в хранилище
# res.public_url — публичный URL после загрузки

# Удалить объект (по public_url или по key)
await storage.delete_object(public_url=res.public_url)
# или
await storage.delete_object(key=res.key)

await storage.aclose()

API

StorageClient(base_url, api_key, timeout=30.0)

Параметр Тип По умолчанию Описание
base_url str обязательный Адрес сервиса opengater-storage
api_key str обязательный Значение заголовка X-API-Key
timeout float 30.0 Таймаут HTTP-запросов (в секундах)

create_upload(content_type, prefix="") -> UploadResult

Отправляет POST /uploads. Возвращает UploadResult с полями:

Поле Тип Описание
upload_url str Presigned-PUT URL — именно сюда грузить файл
key str Ключ объекта в хранилище
public_url str Публичный URL после загрузки

upload_file(content, filename, content_type, prefix="") -> StoredObject

Отправляет POST /uploads/file multipart-запросом. Файл загружается на сервер напрямую — без промежуточного presigned-URL. Возвращает StoredObject:

Поле Тип Описание
key str Ключ объекта в хранилище
public_url str Публичный URL загруженного файла
res = await storage.upload_file(content=b"...", filename="pic.png", content_type="image/png", prefix="news/articles")
# res.key / res.public_url  (StoredObject — без upload_url)

delete_object(public_url=None, key=None) -> None

Отправляет DELETE /objects. Нужно передать хотя бы один из параметров; если не передан ни один — поднимает ValueError.

Важно: при удалении по public_url сервис сам срезает URL до ключа по своей базе. Передавать key надёжнее, если он у вас есть.

aclose() -> None

Закрывает внутренний httpx.AsyncClient. Вызывайте по завершении работы (или используйте клиент через async with).


Ошибки

Все ошибки — наследники StorageError. Библиотека честно поднимает их — best-effort-политику (например, глушить удаление чужого URL) реализует потребитель.

Класс Когда
StorageError База; неожиданный HTTP-статус
StorageBadRequest HTTP 400
StorageAuthError HTTP 401 / 403
StoragePayloadTooLarge HTTP 413 (файл превышает лимит)
StorageUnavailable HTTP 5xx, таймаут, сетевая ошибка

Атрибуты .status_code (int | None) и .detail (str | None) доступны на всех экземплярах.

from opengater_storage_client import StorageClient, StorageAuthError, StorageUnavailable

try:
    res = await storage.create_upload("image/jpeg")
except StorageAuthError as e:
    # неверный ключ
    raise
except StorageUnavailable as e:
    # сервис недоступен или таймаут — логируйте e.detail
    raise

Metadata

Release files for opengater-storage-client 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for opengater-storage-client 0.2.2
File Size Uploaded
opengater_storage_client-0.2.2.tar.gz 6.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for opengater-storage-client 0.2.2
File Interpreter ABI Platform
opengater_storage_client-0.2.2-py3-none-any.whl Python 3 none any Details

Total release size: 12.2 kB

Release files / opengater_storage_client-0.2.2.tar.gz

Download URL opengater_storage_client-0.2.2.tar.gz
Size 6.3 kB
Tags Source
SHA-256 checksum
How to use checksums
a265e4177d8e09a95d14bdf06fcd85c952745e6ec645c4f0632d94b3daaffcc2
BLAKE2b-256 checksum
How to use checksums
fe5c9e849fd54f17321f3cac00088263037f1ee75928f44e925ea9941768dce6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.7 {"installer":{"name":"uv","version":"0.11.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / opengater_storage_client-0.2.2-py3-none-any.whl

Download URL opengater_storage_client-0.2.2-py3-none-any.whl
Size 5.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b56f5814a9406df942b8e62267658cf7bd9557f8f7a722b71c5a086b3640bffe
BLAKE2b-256 checksum
How to use checksums
5cf445818085a1f1e719ca9f0bcd81df21f8f48d08d6697084588cbfb9eca3cf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.7 {"installer":{"name":"uv","version":"0.11.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release history Release notifications | RSS feed

This release

0.2.2 This release

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page