You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
import httpx
|
|
from flask import current_app, has_app_context
|
|
|
|
from .client import ServiceClient
|
|
from .config import ServiceConfig
|
|
from .errors import ServiceConfigError
|
|
|
|
|
|
def init_service_clients(app) -> None:
|
|
configs = app.config.get("SERVICES", {})
|
|
clients: dict[str, ServiceClient] = {}
|
|
for name, value in configs.items():
|
|
if "base_url" not in value:
|
|
raise ServiceConfigError(f"service {name} missing base_url")
|
|
clients[name] = ServiceClient(ServiceConfig.from_mapping(name, value))
|
|
app.extensions["iti_service_clients"] = clients
|
|
|
|
|
|
def register_service_client(
|
|
app,
|
|
name: str,
|
|
config: dict[str, Any],
|
|
*,
|
|
transport: httpx.BaseTransport | None = None,
|
|
) -> ServiceClient:
|
|
client = ServiceClient(ServiceConfig.from_mapping(name, config), transport=transport)
|
|
clients = app.extensions.setdefault("iti_service_clients", {})
|
|
clients[name] = client
|
|
return client
|
|
|
|
|
|
def service_client(name: str) -> ServiceClient:
|
|
if not has_app_context():
|
|
raise ServiceConfigError("service_client() requires an app context")
|
|
clients = current_app.extensions.get("iti_service_clients", {})
|
|
client = clients.get(name)
|
|
if client is None:
|
|
raise ServiceConfigError(f"service client not configured: {name}")
|
|
return client
|