Skip to main content

Python client for Omoide service

Project description

omoide-client

Python-клиент для сервера Omoide.

Генерация клиента

Для создания новой версии требуется запущенный экземпляр Omoide.

openapi-python-client generate --url http://127.0.0.1:8080/api/openapi.json --output-path ./omoide_tmp --overwrite

Мне не удалось добиться от утилиты генерации чистого результата, так что я просто предпочитаю копировать каталог omoide_api_client из того, что было сгенерировано.

Как пользоваться клиентом

Создание экземпляра простого клиента:

from omoide_client import Client

client = Client(base_url='https://api.example.com')

Создание экземпляра клиента с аутентификацией:

from omoide_client import AuthenticatedClient

client = AuthenticatedClient(base_url='https://api.example.com', token='SuperSecretToken')

Использование:

from omoide_client.models import MyDataModel
from omoide_client.api.my_tag import get_my_data_model
from omoide_client.types import Response

with client as client:
    my_data: MyDataModel = get_my_data_model.sync(client=client)
    response: Response[MyDataModel] = get_my_data_model.sync_detailed(client=client)

То же самое, но асинхронно:

from omoide_client.models import MyDataModel
from omoide_client.api.my_tag import get_my_data_model
from omoide_client.types import Response

async with client as client:
    my_data: MyDataModel = await get_my_data_model.asyncio(client=client)
    response: Response[MyDataModel] = await get_my_data_model.asyncio_detailed(client=client)

При необходимости использовать отдельный сертификат для SSL.

from omoide_client import AuthenticatedClient

client = AuthenticatedClient(
    base_url='https://internal_api.example.com', 
    token='SuperSecretToken',
    verify_ssl='/path/to/certificate_bundle.pem',
)

Можно также отключить проверку сертификата (это небезопасно):

from omoide_client import AuthenticatedClient

client = AuthenticatedClient(
    base_url='https://internal_api.example.com', 
    token='SuperSecretToken', 
    verify_ssl=False
)

Стоит иметь в виду:

  1. Все сочетания путь-метод станут модулями с четырьмя функциями:

    1. sync: Блокирующий запрос, возвращающий ответ или None.
    2. sync_detailed: Блокирующий запрос, всегда возвращающий Request (с полем parsed если он был успешен).
    3. asyncio: То же самое, что и sync только неблокирующий.
    4. asyncio_detailed: То же самое, что и sync_detailed только неблокирующий.
  2. Все аргументы пути/тела запроса/строки запроса становятся аргументами метода клиента.

  3. Если у ручки были теги, первый тег становится именем модуля для функции клиента.

  4. Все ручки без тегов окажутся в модуле omoide_client.api.default

Расширенная настройка

Объект Client обладает рядом расширенных настроек, которые можно посмотреть в его коде.

Также есть возможность дополнительной настройки нижележащих httpx.Client или httpx.AsyncClient:

from omoide_client import Client

def log_request(request):
    print(f'Request event hook: {request.method} {request.url} - Waiting for response')

def log_response(response):
    request = response.request
    print(f'Response event hook: {request.method} {request.url} - Status {response.status_code}')

client = Client(
    base_url='https://api.example.com',
    httpx_args={'event_hooks': {'request': [log_request], 'response': [log_response]}},
)

# Or get the underlying httpx client to modify directly with client.get_httpx_client() or client.get_async_httpx_client()

Существует также возможность замены клиента httpx, но это собьёт все настройки:

import httpx
from omoide_client import Client

client = Client(
    base_url='https://api.example.com',
)
# Note that base_url needs to be re-set, as would any shared cookies, headers, etc.
client.set_httpx_client(httpx.Client(base_url='https://api.example.com', proxies='http://localhost:8030'))

Публикация клиента

uv build
uv publish --token <token>

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

omoide_client-0.3.12.tar.gz (35.3 kB view details)

Uploaded Source

Built Distribution

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

omoide_client-0.3.12-py3-none-any.whl (108.1 kB view details)

Uploaded Python 3

File details

Details for the file omoide_client-0.3.12.tar.gz.

File metadata

  • Download URL: omoide_client-0.3.12.tar.gz
  • Upload date:
  • Size: 35.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.9

File hashes

Hashes for omoide_client-0.3.12.tar.gz
Algorithm Hash digest
SHA256 e16607766bfff8216b4846b76139e25a955cdae3f7e73214510202d646307c19
MD5 3015ddbacdd0a6f9d89b91c13ae62b8c
BLAKE2b-256 09e9e6667bd93c195fa63452fbc5f04ade8c138e24e92d43f7c8ca514ba9217e

See more details on using hashes here.

File details

Details for the file omoide_client-0.3.12-py3-none-any.whl.

File metadata

File hashes

Hashes for omoide_client-0.3.12-py3-none-any.whl
Algorithm Hash digest
SHA256 179acdaffd1e01d3ad875a785f2c8788bb907d6ef539969593cba6066c5d6a58
MD5 e139a3843594772504876796777c620e
BLAKE2b-256 d1c72a5da9fa2ca890a9e305259840f5d2698a2e64b41a94577177a8ed868394

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