40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
import logging
|
|
|
|
from fastapi import HTTPException
|
|
|
|
from .base import ClienteBase
|
|
|
|
_CLIENTES: dict[str, ClienteBase] = {}
|
|
|
|
|
|
def registrar(cliente: ClienteBase) -> ClienteBase:
|
|
"""Chamado no fim do modulo de cada cliente (app/v1/<cliente>/cliente.py)."""
|
|
chave = cliente.nome.lower()
|
|
if chave in _CLIENTES:
|
|
logging.warning(f"Cliente '{chave}' registrado mais de uma vez, sobrescrevendo")
|
|
_CLIENTES[chave] = cliente
|
|
return cliente
|
|
|
|
|
|
def obter(nome: str) -> ClienteBase:
|
|
if cliente := _CLIENTES.get(nome.lower()):
|
|
return cliente
|
|
raise HTTPException(
|
|
status_code=404, detail=f"cliente '{nome}' nao atendido por esta API"
|
|
)
|
|
|
|
|
|
def listar() -> list[str]:
|
|
return sorted(_CLIENTES)
|
|
|
|
|
|
def get_cliente(cliente: str) -> ClienteBase:
|
|
"""
|
|
Dependencia do FastAPI. Resolve o cliente pelo path param da rota:
|
|
|
|
@router.post("/{cliente}/compras/dados")
|
|
async def rota(cli: ClienteBase = Depends(get_cliente)): ...
|
|
|
|
O nome do parametro tem que ser `cliente` pra bater com o {cliente} da rota.
|
|
"""
|
|
return obter(cliente)
|