Skip to content

Reference

Translator

Translator(
    default_language: str,
    languages: tuple[str, ...],
    fallback_languages: dict[str, tuple[str, ...]] | None = None,
)

A translator object that manages translations for registered SQLModel classes.

Parameters:

  • default_language

    (str) –

    The language to use if no language was set externally.

  • languages

    (tuple[str, ...]) –

    All supported languages i.e the translations you want to store.

  • fallback_languages

    (dict[str, tuple[str, ...]] | None, default: None ) –

    Fallbacks for each language used when the active language is not in languages. An example: { 'default': ('en', 'pl', 'de'), 'fr': 'es' }. The default key is required.

Raises:

Methods:

  • register

    Register a SQLModel class for translations.

Source code in src/modeltranslation/translator.py
def __init__(
    self,
    default_language: str,
    languages: tuple[str, ...],
    fallback_languages: dict[str, tuple[str, ...]] | None = None,
) -> None:
    """Construct a translator object.

    Args:
        default_language (str): The language to use if no language was set externally.

        languages (tuple[str, ...]): All supported languages i.e the translations you want to store.

        fallback_languages (dict[str, tuple[str, ...]] | None): Fallbacks for each language
            used when the active language is not in `languages`. An example:
            `{
              'default': ('en', 'pl', 'de'),
              'fr': 'es'
            }`.
            The default key is required.

    Raises:
        ImproperlyConfiguredError: If the configuration is internally inconsistent.

    """
    self._active_language: ContextVar[str] = ContextVar("current_locale", default=default_language)

    self._default_language: str = default_language

    self._languages: tuple[str, ...] = languages

    # fallbacks for untranslated languages
    self._fallback_languages: dict[str, tuple[str, ...]] = {"default": (self._default_language,)}
    if fallback_languages:
        self._fallback_languages = fallback_languages

    self._validate_translator_object()

register

register(model: type[SQLModel]) -> Callable

Register a SQLModel class for translations.

This function returns a decorator that applies TranslationOptions to the given SQLModel class. After applying, the model will have translation accessors and metadata set up automatically.

Parameters:

  • model

    (SQLModel) –

    the class to apply translations on.

Raises:

Examples:

>>> from sqlmodel import SQLModel
>>> from modeltranslation import Translator
...
>>> class Book(SQLModel, table=True):
...     title: str
...
>>> translator = Translator(
...     default_language="en",
...     languages=("en", "pl"))
...
>>> @translator.register(Book)
... class BookTranslationOptions(TranslationOptions):
...     fields=('title',)
Source code in src/modeltranslation/translator.py
def register(self, model: type[SQLModel]) -> Callable:
    """Register a SQLModel class for translations.

    This function returns a decorator that applies `TranslationOptions`
    to the given SQLModel class. After applying, the model
    will have translation accessors and metadata set up automatically.

    Args:
        model (SQLModel): the class to apply translations on.

    Raises:
        ImproperlyConfiguredError: If the translation options are inconsistent with the Translator.

    Examples:
        >>> from sqlmodel import SQLModel
        >>> from modeltranslation import Translator
        ...
        >>> class Book(SQLModel, table=True):
        ...     title: str
        ...
        >>> translator = Translator(
        ...     default_language="en",
        ...     languages=("en", "pl"))
        ...
        >>> @translator.register(Book)
        ... class BookTranslationOptions(TranslationOptions):
        ...     fields=('title',)

    """

    def decorator(options: TranslationOptions) -> None:
        self._replace_accessors(model, options)
        self._rebuild_model(model, options)

    return decorator

TranslationOptions

Base class for configuring the translation of SQLModel classes.

This class defines which fields are translated, which translations are required and how to handle missing values.

Examples:

>>> from modeltranslation import TranslationOptions
>>> class BookTranslationOptions(TranslationOptions):
...     fields = ("title",)
...     required_languages = ("en",)

Attributes:

fallback_languages class-attribute instance-attribute

fallback_languages: dict[str, tuple[str, ...]] | None = None

Languages to use when the current language is missing.

Example

('en', 'pl', 'de')

The fallbacks can be also specified with a dictionary. The default key is required.

Example
{
  'default': ('en', 'pl', 'de'),
  'fr': 'es'
}

fallback_values class-attribute instance-attribute

fallback_values: dict[str, Any] | Any = None

The values to use if all fallback languages yielded no value.

Example

('No translation provided')

It's also possible to specify a fallback value for each field.

Example
{
  'title': ('No translation'),
  'author': ('No translation provided')
}

fields class-attribute instance-attribute

fields: tuple[str, ...] = ()

Names of fields to translate.

Example

(title,description)

required_languages class-attribute instance-attribute

required_languages: dict[str, tuple[str, ...]] | tuple[str, ...] | None = None

The required translations for this class.

This also affects the pydantic model and typehints.

Example

('en',)

The fallbacks can be also specified with a dictionary. This makes it possible to set the requirements per field.

Example
{
  'en': ('title', 'author'),
  'default': ('title',)
}

The default key is required. For english, title and author are required. For all other languages only title is required.

apply_translation

apply_translation(app: FastAPI, translator: Translator) -> None

Configure the app set the current language as a context variable.

Applies middleware to FastAPI app which sets language based on the accept-language HTTP header. The resolved language is stored in the translator per execution context.

Parameters:

  • app

    (FastAPI) –

    FastAPI application.

  • translator

    (Translator) –

    The translator used to register translations in this app.

Examples:

>>> from fastapi import FastAPI
>>> from modeltranslation import Translator, apply_translation
...
>>> translator = Translator(
...     default_language="en",
...     languages=("en", "pl"),
... )
>>> app = FastAPI()
>>> apply_translation(app, translator)
Note

In a typical use case, you would register translations with the translator before calling this function.

Source code in src/modeltranslation/fastapi_middleware.py
def apply_translation(app: FastAPI, translator: Translator) -> None:
    """Configure the app set the current language as a context variable.

    Applies middleware to FastAPI app which sets language based on the accept-language HTTP header.
    The resolved language is stored in the translator per execution context.

    Args:
        app (FastAPI): FastAPI application.
        translator (Translator): The translator used to register translations in this app.

    Examples:
        >>> from fastapi import FastAPI
        >>> from modeltranslation import Translator, apply_translation
        ...
        >>> translator = Translator(
        ...     default_language="en",
        ...     languages=("en", "pl"),
        ... )
        >>> app = FastAPI()
        >>> apply_translation(app, translator)

    Note:
        In a typical use case, you would register translations with
        the translator before calling this function.

    """

    @app.middleware("http")
    async def set_locale_context(request: Request, call_next):
        header = request.headers.get("accept-language")
        locale = header.split(",") if header else None
        if locale:
            for entry in locale:
                lang = entry.split(";")
                if lang[0] in translator.get_languages():
                    translator.set_active_language(str(lang[0]))
                    break
        return await call_next(request)

ImproperlyConfiguredError

ImproperlyConfiguredError(message: str)

Raised when the configuration is internally inconsistent.

Source code in src/modeltranslation/exceptions.py
def __init__(self, message: str) -> None:
    super().__init__(message)