1
0
mirror of https://github.com/ijaric/voice_assistant.git synced 2025-05-24 06:23:28 +00:00

build: wip: joke example

This commit is contained in:
Artem Litvinov 2023-09-30 22:28:55 +01:00
parent 9888f0e993
commit bf7807899c
8 changed files with 72 additions and 5 deletions

View File

@ -1,5 +1,6 @@
from .health import *
from .joke import get_joke, joke_router
__all__ = [
"basic_router",
"basic_router", "joke_router", "get_joke"
]

View File

@ -0,0 +1,22 @@
import fastapi
import lib.api.v1.schemas as api_shemas
import lib.joke.services as services
joke_router = fastapi.APIRouter()
@joke_router.get(
"/",
response_model=api_shemas.JokeResponse,
summary="Random joke",
description="Return a random joke from a free API.",
)
async def get_joke(joke_service: services.JokeService):
joke = await joke_service.get_joke()
if joke:
return api_shemas.JokeResponse(
joke=f"{joke.setup}\n{joke.punchline}", id=joke.id_field, category=joke.type_field
)
return api_shemas.JokeResponse(joke="No joke for you!", id=0, category="No category")

View File

@ -1,5 +1,4 @@
from .base import HealthResponseModel
from .joke import JokeResponse
__all__ = [
"HealthResponseModel",
]
__all__ = ["HealthResponseModel", "JokeResponse"]

View File

@ -0,0 +1,7 @@
import pydantic
class JokeResponse(pydantic.BaseModel):
id_field: int = pydantic.Field(alias="id")
joke: str
category: str

View File

@ -11,6 +11,7 @@ import lib.app.errors as app_errors
import lib.app.settings as app_settings
import lib.app.split_settings as app_split_settings
import lib.clients as clients
import lib.joke.services as joke_services
logger = logging.getLogger(__name__)
@ -69,12 +70,13 @@ class Application:
# Services
logger.info("Initializing services")
jk_serivces = joke_services.JokeService(http_client=http_client)
# Handlers
logger.info("Initializing handlers")
liveness_probe_handler = api_v1_handlers.basic_router
joke_handler = api_v1_handlers.get_joke(joke_service=jk_serivces)
logger.info("Creating application")

View File

@ -0,0 +1,3 @@
from .services import JokeService
__all__ = ["JokeService"]

View File

@ -0,0 +1,23 @@
import logging
import httpx
import pydantic
import lib.models.joke as joke_models
class JokeService:
def __init__(self, http_client: httpx.AsyncClient):
self.http_client = http_client
self.logger = logging.getLogger(__name__)
async def get_joke(self) -> joke_models.Joke | None:
try:
async with self.http_client as client:
response = await client.get("https://official-joke-api.appspot.com/random_joke")
content = response.json()
return joke_models.Joke(**content)
except pydantic.ValidationError as error:
self.logger.exception("Validation Error: %s", error)
except httpx.HTTPError as error:
self.logger.exception("HTTP Error: %s", error)

View File

@ -0,0 +1,10 @@
import pydantic
class Joke(pydantic.BaseModel):
"""Joke model."""
id_field: int = pydantic.Field(alias="id")
type_field: str = pydantic.Field(alias="type")
setup: str
punchline: str