Skip to main content

Client library for the opengater-storage service

Project description

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 после загрузки

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
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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

opengater_storage_client-0.1.0.tar.gz (5.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

opengater_storage_client-0.1.0-py3-none-any.whl (5.1 kB view details)

Uploaded Python 3

File details

Details for the file opengater_storage_client-0.1.0.tar.gz.

File metadata

  • Download URL: opengater_storage_client-0.1.0.tar.gz
  • Upload date:
  • Size: 5.0 kB
  • Tags: Source
  • Uploaded using 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}

File hashes

Hashes for opengater_storage_client-0.1.0.tar.gz
Algorithm Hash digest
SHA256 e36c884d1dc0bfdae46b6353d9bd0471d418549d1f37d2012ce21614810fc3dc
MD5 eb6b9783c021b6e0f10bef2482ae017a
BLAKE2b-256 cd77e1ecfd6f461515766a91873174e9c88538db52ebdd7b6d118e1dce001076

See more details on using hashes here.

File details

Details for the file opengater_storage_client-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: opengater_storage_client-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 5.1 kB
  • Tags: Python 3
  • Uploaded using 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}

File hashes

Hashes for opengater_storage_client-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7c7bbae6ad5fd847c1a3dd4eec593aa3d3f03619492bd747a129f949db54111b
MD5 ce9bbe44592cbe01be9d4455122a8485
BLAKE2b-256 a1a40d096a09f917b309ac46b853b0a88bf2fb09fa5ae02d6da939db6c3a10ab

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page