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

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

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.2.0.tar.gz (5.8 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.2.0-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: opengater_storage_client-0.2.0.tar.gz
  • Upload date:
  • Size: 5.8 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.2.0.tar.gz
Algorithm Hash digest
SHA256 9efe6629f5e671aaff2ada413b28307f91f408d44eefdc94a1e5249659db12e8
MD5 d0845c08dc07392b11f99b3706dcc311
BLAKE2b-256 cea496368320fe823d39584422800b7f9622440699713809187cec6cbde15f38

See more details on using hashes here.

File details

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

File metadata

  • Download URL: opengater_storage_client-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 5.5 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.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1ed939f49040fe96ae9baffdcd5d908cfcab96e1c99ee8a24f2a02f86380b547
MD5 7cd8c6cea4937f9da7bf6fa736d1468b
BLAKE2b-256 2c514b022d8af4946a58fdf8b26d6d41ca088dcf1a44150b1e0f54a85984d522

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