tmpl-fastapi/app/respond.py

78 lines
2.1 KiB
Python
Raw Normal View History

import os
import mimetypes
from typing import Optional, Mapping
from fastapi import Response
from fastapi.responses import FileResponse
from starlette.background import BackgroundTask
from .common import templates
def with_tmpl(
name: str,
code: int = 200,
headers: Optional[Mapping[str, str]] = None,
background: Optional[BackgroundTask] = None,
**context) -> Response:
"""Render a Jinja2 template and return Response object.
`response_class` parameter is not needed
Args:
name (str): Template filename
code (int, optional): HTTP response code
headers (Optional[Mapping[str, str]], optional):
Additional headers, passed to Response constructor
background (Optional[BackgroundTask], optional):
Background task, passed to Response constructor
Returns:
FastAPI's TemplateResponse object
"""
return templates.TemplateResponse(
name=name,
context=context,
status_code=code,
headers=headers,
background=background,
)
def with_file(
path: os.PathLike,
mime: Optional[str] = None,
code: int = 200,
headers: Optional[Mapping[str, str]] = None,
background: Optional[BackgroundTask] = None) -> FileResponse:
"""Send a file specified in `path`
automatically guessing mimetype if `mime` is None
Args:
path (os.PathLike): File path
mime (Optional[str], optional): File mimetype
code (int, optional): HTTP response code
headers (Optional[Mapping[str, str]], optional):
Additional headers, passed to Response constructor
background (Optional[BackgroundTask], optional):
Background task, passed to Response constructor
Returns:
FileResponse: FastAPI's FileResponse object
"""
return FileResponse(
path=path,
media_type=(
mime or
mimetypes.guess_type(path)[0]
),
status_code=code,
headers=headers,
background=background,
)
# Alias
with_template = with_tmpl