### Example Usage of BabelLoader
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
This Python script demonstrates how to use the BabelLoader with pydantic-i18n. It assumes a specific translations directory structure and requires Babel to be installed.
```python
from pydantic_i18n import PydanticI18n
pydantic_i18n = PydanticI18n(loader_cls='BabelLoader')
@pydantic_i18n('hello')
class HelloModel:
message: str
hello_model = HelloModel()
print(hello_model.message)
hello_model_de = HelloModel()
hello_model_de.locale = 'de_DE'
print(hello_model_de.message)
hello_model_en = HelloModel()
hello_model_en.locale = 'en_US'
print(hello_model_en.message)
```
--------------------------------
### DictLoader Example (Python)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Illustrates the usage of DictLoader, the default loader for PydanticI18n. It allows direct use of translation dictionaries without additional setup.
```Python
from fastapi import FastAPI
from pydantic import BaseModel
from pydantic_i18n import PydanticI18n, DictLoader
app = FastAPI()
class Item(BaseModel):
name: str
# Define translations directly in a dictionary
translations = {
'en_US': {
'Item': {
'name': {
'missing': 'Item name is required'
}
}
},
'de_DE': {
'Item': {
'name': {
'missing': 'Der Artikelname ist erforderlich'
}
}
}
}
# Use DictLoader with the translations
app.i18n = PydanticI18n(loader=DictLoader(translations=translations))
@app.post('/items')
def create_item(item: Item):
return item
```
--------------------------------
### Run Uvicorn Server for Example App
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
This command runs a Python application using Uvicorn, a popular ASGI server. It's commonly used for FastAPI applications. The `--reload` flag enables live-reloading, automatically restarting the server when code changes are detected. This example shows how to run a tutorial application named `tutorial001`.
```console
$ uvicorn tutorial001:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
```
--------------------------------
### Install Babel for BabelLoader
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
This command installs the Babel library, which is a dependency for using the BabelLoader in pydantic-i18n. Babel is required for handling translations.
```bash
(venv) $ pip install babel
```
--------------------------------
### Install pydantic-i18n using pip
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
This command installs the pydantic-i18n package using pip. Ensure you have Python 3.8+ and pip installed.
```console
$ pip install pydantic-i18n
---> 100%
```
--------------------------------
### Install Flit Package Manager
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Installs the Flit package manager, which is used by pydantic-i18n for building, packaging, and publishing. It's recommended to install Flit after activating the virtual environment.
```console
pip install flit
---> 100%
```
--------------------------------
### JsonLoader Example (Python)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Demonstrates how to use JsonLoader to load translations from JSON files organized in a specific directory structure. Each JSON file corresponds to a locale.
```Python
from fastapi import FastAPI
from pydantic import BaseModel
from pydantic_i18n import PydanticI18n, JsonLoader
app = FastAPI()
class Item(BaseModel):
name: str
# Assuming translations are in a 'translations' directory
# with files like en_US.json and de_DE.json
app.i18n = PydanticI18n(loader=JsonLoader(path='translations'))
@app.post('/items')
def create_item(item: Item):
return item
```
--------------------------------
### Install Typer CLI Autocompletion
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
This command installs shell completion for Typer CLI, enabling autocompletion for commands in your terminal. After installation, restart your terminal for the changes to take effect. This is an optional step for enhanced command-line usability.
```console
$ typer --install-completion
zsh completion installed in /home/user/.bashrc.
Completion will take effect once you restart the terminal.
```
--------------------------------
### MkDocs Configuration Example (YAML)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Illustrates a snippet from an MkDocs configuration file, specifically showing how navigation items are defined. This is relevant when adding new pages or translating existing ones to ensure correct structure and ordering within the documentation.
```yaml
site_name: pydantic-i18n
# More stuff
nav:
- index.md
- Languages:
- en: /
- ru: /ru/
```
--------------------------------
### Install Development Dependencies with Flit
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Installs the project's development dependencies and the local pydantic-i18n package into the activated virtual environment. The `--symlink` option (or `--pth-file` on Windows) allows for live testing of code changes without reinstallation.
```console
flit install --deps develop --symlink
---> 100%
```
```console
flit install --deps develop --pth-file
---> 100%
```
--------------------------------
### Basic Pydantic v2 Dictionary Loader Example
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Demonstrates how to use pydantic-i18n with a dictionary loader for Pydantic v2. It shows creating a translation dictionary and using the PydanticI18n class to translate validation errors.
```Python
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n
class User(BaseModel):
name: str
age: int
translations = {
"en": {
"validation_errors": {
"name": {
"required": "Name is required.",
"max_length": "Name cannot be longer than {limit_value} characters.",
},
"age": {
"required": "Age is required.",
"greater_than": "Age must be greater than {limit_value}.",
},
}
},
"es": {
"validation_errors": {
"name": {
"required": "Se requiere el nombre.",
"max_length": "El nombre no puede tener más de {limit_value} caracteres.",
},
"age": {
"required": "Se requiere la edad.",
"greater_than": "La edad debe ser mayor que {limit_value}.",
},
}
},
}
pydantic_i18n = PydanticI18n(locales=translations)
try:
User(name="", age=10)
except ValidationError as e:
errors = e.errors()
translated_errors_en = pydantic_i18n.translate(errors, locale="en")
print("--- English ---")
print(translated_errors_en)
translated_errors_es = pydantic_i18n.translate(errors, locale="es")
print("\n--- Spanish ---")
print(translated_errors_es)
```
--------------------------------
### JSON Translations Example
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Example of a JSON file containing English translations for Pydantic error messages.
```json
{
"Item": {
"name": {
"missing": "Item name is required"
}
}
}
```
--------------------------------
### Serve Documentation Live with MkDocs
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
This command uses the `docs.py` script to serve the MkDocs documentation locally. It watches for file changes and reloads the site automatically, providing a live development environment. Ensure all project requirements are installed before running.
```console
$ python ./scripts/docs.py live
[INFO] Serving on http://127.0.0.1:8008
[INFO] Start watching changes
[INFO] Start detecting changes
```
--------------------------------
### German JSON Translations Example
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Example of a JSON file containing German translations for Pydantic error messages.
```json
{
"Item": {
"name": {
"missing": "Der Artikelname ist erforderlich"
}
}
}
```
--------------------------------
### Serve Live Documentation for Existing Language (Python)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Starts a live server to preview documentation changes for a specific language. It requires the 'live' command and the 2-letter language code as a CLI argument. The server will then serve the documentation at http://127.0.0.1:8008, reflecting changes as they are saved.
```console
# Use the command "live" and pass the language code as a CLI argument
$ python ./scripts/docs.py live ru
```
--------------------------------
### Run Uvicorn Server
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Starts the Uvicorn development server for the FastAPI application. The `--reload` flag enables automatic server restarts upon code changes, which is useful during development.
```console
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
--------------------------------
### Verify Pip in Virtual Environment
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Confirms that the virtual environment's pip executable is being used. This is a crucial step to ensure that packages are installed within the isolated environment.
```console
which pip
some/directory/pydantic-i18n/env/bin/pip
```
```powershell
Get-Command pip
some/directory/pydantic-i18n/env/bin/pip
```
--------------------------------
### Activate Python Virtual Environment
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Activates the created virtual environment. Different commands are used for Linux/macOS, Windows PowerShell, and Windows Bash. Activation ensures that installed packages and executables are sourced from the virtual environment.
```console
source ./env/bin/activate
```
```powershell
.\env\Scripts\Activate.ps1
```
```bash
source ./env/Scripts/activate
```
--------------------------------
### Create Python Virtual Environment with venv
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Creates an isolated Python environment named 'env' in the current directory. This isolates project dependencies from the global Python installation.
```console
python -m venv env
```
--------------------------------
### FastAPI Translation Configuration (tr.py)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Sets up translation configurations for a FastAPI application using pydantic-i18n. It defines a translation dictionary and a dependency function to get the current locale.
```Python
from fastapi import FastAPI, Depends
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n
from typing import Dict, Any
class User(BaseModel):
name: str
age: int
translations: Dict[str, Dict[str, Dict[str, Any]]] = {
"en": {
"validation_errors": {
"name": {
"required": "Name is required.",
"max_length": "Name cannot be longer than {limit_value} characters.",
},
"age": {
"required": "Age is required.",
"greater_than": "Age must be greater than {limit_value}.",
},
}
},
"es": {
"validation_errors": {
"name": {
"required": "Se requiere el nombre.",
"max_length": "El nombre no puede tener más de {limit_value} caracteres.",
},
"age": {
"required": "Se requiere la edad.",
"greater_than": "La edad debe ser mayor que {limit_value}.",
},
}
},
}
pydantic_i18n = PydanticI18n(locales=translations)
def get_locale(locale: str = "en") -> str:
return locale
def validation_exception_handler(request, exc: ValidationError):
errors = exc.errors()
locale = get_locale()
translated_errors = pydantic_i18n.translate(errors, locale=locale)
return JSONResponse(content=translated_errors, status_code=422)
```
--------------------------------
### Format Code with format.sh Script
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Executes a bash script to format and clean all project code, including auto-sorting imports. This script requires the pydantic-i18n package to be installed locally in the environment.
```bash
bash scripts/format.sh
```
--------------------------------
### Get Pydantic Error Strings (Python)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Shows how to retrieve default English error messages directly from Pydantic using PydanticI18n.get_pydantic_messages. The output can be a dictionary, JSON string, or Babel format.
```Python
from pydantic_i18n import PydanticI18n
# Get messages as a dictionary (default)
messages_dict = PydanticI18n.get_pydantic_messages()
print(messages_dict)
# Get messages as a JSON string
messages_json = PydanticI18n.get_pydantic_messages(output='json')
print(messages_json)
# Get messages in Babel format
messages_babel = PydanticI18n.get_pydantic_messages(output='babel')
print(messages_babel)
```
--------------------------------
### FastAPI App Setup with Pydantic Validation Errors
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
This snippet demonstrates setting up a FastAPI application with Pydantic models and custom exception handling for validation errors. It includes a basic user creation endpoint and shows how validation errors are returned in German.
```python
from fastapi import FastAPI, Depends
from pydantic import BaseModel, ValidationError
from fastapi.exceptions import RequestValidationError
# Assume get_locale and validation_exception_handler are defined elsewhere
# from .utils import get_locale, validation_exception_handler
# Mock implementations for demonstration
def get_locale():
# In a real app, this would determine the user's locale
return "de_DE"
def validation_exception_handler(request, exc):
# In a real app, this would translate the exception
return {"detail": exc.errors()}
app = FastAPI(dependencies=[Depends(get_locale)])
app.add_exception_handler(RequestValidationError, validation_exception_handler)
class User(BaseModel):
name: str
age: int
@app.post("/user", response_model=User)
def create_user(user: User):
return user
# Usage:
# curl -X POST 'http://localhost:8000/user?locale=de_DE' \
# -H 'Content-Type: application/json' \
# -d '{}'
#
# Response:
# {
# "detail": [
# {"loc": ["body", "name"], "msg": "Feld erforderlich", "type": "missing"},
# {"loc": ["body", "age"], "msg": "Feld erforderlich", "type": "missing"}
# ]
# }
```
--------------------------------
### Implement Custom Translation Loader with BaseLoader
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Explains how to create custom translation loaders by inheriting from the BaseLoader abstract class. This allows support for any storage backend, such as databases, remote APIs, or CSV files. The example demonstrates a CsvLoader.
```python
import os
from typing import List, Dict
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n, BaseLoader
class CsvLoader(BaseLoader):
"""Custom loader that reads translations from CSV files."""
def __init__(self, directory: str):
self.directory = directory
@property
def locales(self) -> List[str]:
"""Return list of available locales from CSV filenames."""
return [
filename[:-4] # Remove .csv extension
for filename in os.listdir(self.directory)
if filename.endswith(".csv")
]
def get_translations(self, locale: str) -> Dict[str, str]:
"""Load translations from CSV file for given locale."""
with open(os.path.join(self.directory, f"{locale}.csv")) as fp:
# CSV format: original_message,translated_message
data = dict(line.strip().split(",") for line in fp)
return data
# Directory structure:
# translations/
# ├── en_US.csv -> "Field required,field required"
# └── de_DE.csv -> "Field required,Feld erforderlich"
loader = CsvLoader("./translations")
tr = PydanticI18n(loader)
class Customer(BaseModel):
name: str
try:
Customer()
except ValidationError as e:
translated = tr.translate(e.errors(), locale="de_DE")
print(translated)
```
--------------------------------
### Create Custom CSV Loader for Translations
Source: https://github.com/boardpack/pydantic-i18n/blob/master/README.md
Provides an example of creating a custom loader by inheriting from BaseLoader. This CSV loader reads translations from CSV files, mapping keys to values for specific locales.
```python
import os
from typing import List, Dict
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n, BaseLoader
class CsvLoader(BaseLoader):
def __init__(self, directory: str):
self.directory = directory
@property
def locales(self) -> List[str]:
return [
filename[:-4]
for filename in os.listdir(self.directory)
if filename.endswith(".csv")
]
def get_translations(self, locale: str) -> Dict[str, str]:
with open(os.path.join(self.directory, f"{locale}.csv")) as fp:
data = dict(line.strip().split(",") for line in fp)
return data
class User(BaseModel):
name: str
if __name__ == '__main__':
loader = CsvLoader("./translations")
tr = PydanticI18n(loader)
try:
User()
except ValidationError as e:
translated_errors = tr.translate(e.errors(), locale="de_DE")
print(translated_errors)
# [
# {
# 'type': 'missing',
# 'loc': ('name',),
# 'msg': 'Feld erforderlich',
# 'input': {
#
# },
# 'url': 'https://errors.pydantic.dev/2.6/v/missing'
# }
# ]
```
--------------------------------
### Translate Pydantic Errors with BabelLoader
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Shows how to integrate pydantic-i18n with Babel for professional translation workflows using .po and .mo files. This is suitable for projects already using Babel for internationalization. Requires pip install babel.
```python
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n, BabelLoader
# Initialize Babel loader
# Requires: pip install babel
loader = BabelLoader("./translations")
# Or specify custom domain (default is "messages")
loader = BabelLoader("./translations", domain="pydantic_errors")
tr = PydanticI18n(loader)
class Order(BaseModel):
product_id: int
quantity: int
try:
Order()
except ValidationError as e:
translated = tr.translate(e.errors(), locale="de_DE")
print(translated)
```
--------------------------------
### Get Pydantic Messages Utility
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Explains the `get_pydantic_messages()` class method, which extracts all current error message templates from Pydantic. This utility is useful for generating comprehensive translation dictionaries. It supports outputting messages as a dictionary, a JSON string, or in Babel PO format.
```python
from pydantic_i18n import PydanticI18n
# Get messages as dictionary (default)
messages_dict = PydanticI18n.get_pydantic_messages()
print(messages_dict)
# {
# "Object has no attribute '{}'": "Object has no attribute '{}'",
# "Invalid JSON: {}": "Invalid JSON: {}",
# "JSON input should be string, bytes or bytearray": "...",
# "Recursion error - cyclic reference detected": "...",
# "Field required": "Field required",
# "Field is frozen": "Field is frozen",
# ...
# }
# Get messages as JSON string
messages_json = PydanticI18n.get_pydantic_messages(output="json")
print(messages_json)
# {
# "Field required": "Field required",
# "Field is frozen": "Field is frozen",
# "Error extracting attribute: {}": "Error extracting attribute: {}",
# ...
# }
# Get messages in Babel PO format for .po files
messages_babel = PydanticI18n.get_pydantic_messages(output="babel")
print(messages_babel)
# msgid "Field required"
# msgstr "Field required"
#
# msgid "Field is frozen"
# msgstr "Field is frozen"
#
# msgid "Error extracting attribute: {}"
# msgstr "Error extracting attribute: {}"
# ...
# Use extracted messages to create translation template
english_messages = PydanticI18n.get_pydantic_messages()
translations = {
"en_US": english_messages,
"de_DE": {key: key for key in english_messages}, # Copy keys, translate values later
}
```
--------------------------------
### MkDocs Theme Language Configuration (YAML)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Demonstrates how to configure the theme's language setting within an MkDocs configuration file. This is particularly useful when encountering 'TemplateNotFound' errors for a specific language, allowing you to revert to a supported language like English ('en') while translating content.
```yaml
site_name: pydantic-i18n
# More stuff
theme:
# More stuff
language: xx
```
--------------------------------
### Pydantic-i18n Placeholder Usage (Python)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Demonstrates how to use placeholders within error strings in Pydantic models for internationalization. Placeholders must be enclosed in curly braces {}.
```Python
from fastapi import FastAPI
from pydantic import BaseModel, Field
from pydantic_i18n import PydanticI18n
app = FastAPI()
class User(BaseModel):
name: str = Field(..., description='Your name')
class Config:
# Use pydantic-i18n for validation messages
i18n = PydanticI18n(
locales=['en_US', 'de_DE'],
# Use placeholders in error messages
error_messages={
'en_US': {
'User': {
'name': {
'missing': 'The {name} field is required'
}
}
},
'de_DE': {
'User': {
'name': {
'missing': 'Das Feld {name} wird benötigt'
}
}
}
}
)
@app.post('/user')
def create_user(user: User):
return user
```
--------------------------------
### Create a Custom Loader from CSV
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
This Python script shows how to create a custom loader for pydantic-i18n by inheriting from BaseLoader and implementing the 'locales' property and 'get_translations' method. It demonstrates loading translations from CSV files.
```python
from pydantic_i18n import PydanticI18n, BaseLoader
import csv
class CsvLoader(BaseLoader):
def __init__(self, locales_dir: str, domain: str = 'messages'):
self.locales_dir = locales_dir
self.domain = domain
@property
def locales(self):
return [locale.split('.')[0] for locale in os.listdir(self.locales_dir)]
def get_translations(self, locale: str):
translations = {}
with open(os.path.join(self.locales_dir, f'{locale}.csv'), 'r') as f:
for row in csv.DictReader(f):
translations[row['key']] = row['value']
return translations
pydantic_i18n = PydanticI18n(loader_cls=CsvLoader, loader_kwargs={'locales_dir': './translations/'})
@pydantic_i18n('hello')
class HelloModel:
message: str
hello_model = HelloModel()
print(hello_model.message)
hello_model_de = HelloModel()
hello_model_de.locale = 'de_DE'
print(hello_model_de.message)
hello_model_en = HelloModel()
hello_model_en.locale = 'en_US'
print(hello_model_en.message)
```
--------------------------------
### Format Imports with format-imports.sh Script
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Runs a script specifically designed to format imports and remove unused ones. This script can take longer to run and is recommended for use before committing changes.
```bash
bash scripts/format-imports.sh
```
--------------------------------
### Generate New Translation Directory (Python)
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/contributing.md
Creates a new directory structure for a language that does not yet have any translations. This command, 'new-lang', takes the 2-letter language code as an argument and initializes the necessary files and directories, including updating the main language configuration.
```console
# Use the command new-lang, pass the language code as a CLI argument
$ python ./scripts/docs.py new-lang ht
```
--------------------------------
### Use BabelLoader for Translations
Source: https://github.com/boardpack/pydantic-i18n/blob/master/README.md
Demonstrates how to initialize PydanticI18n with BabelLoader to translate validation errors. It requires a specific directory structure for translation files (.mo, .po).
```python
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n, BabelLoader
loader = BabelLoader("./translations")
tr = PydanticI18n(loader)
class User(BaseModel):
name: str
try:
User()
except ValidationError as e:
translated_errors = tr.translate(e.errors(), locale="de_DE")
print(translated_errors)
# [
# {
# 'type': 'missing',
# 'loc': ('name',),
# 'msg': 'Feld erforderlich',
# 'input': {
#
# },
# 'url': 'https://errors.pydantic.dev/2.6/v/missing'
# }
# ]
```
--------------------------------
### Placeholder Support in Pydantic Error Translations
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Illustrates how to use placeholders (e.g., `{}`) within translation keys to handle dynamic values in Pydantic error messages. The library automatically manages the extraction and reinsertion of these placeholder values during translation.
```python
from decimal import Decimal
from pydantic import BaseModel, ValidationError, Field
from pydantic_i18n import PydanticI18n
```
--------------------------------
### Translate Pydantic Errors with JsonLoader
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Demonstrates how to use JsonLoader to load translations from JSON files and translate Pydantic validation errors to a specified locale (e.g., German). Requires the pydantic and pydantic-i18n libraries.
```python
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n, JsonLoader
# Optionally specify encoding for non-UTF8 files
loader = JsonLoader("./translations", encoding="utf-8")
tr = PydanticI18n(loader)
class UserProfile(BaseModel):
username: str
age: int
try:
UserProfile()
except ValidationError as e:
# Translate to German
de_errors = tr.translate(e.errors(), locale="de_DE")
print(de_errors)
# List available locales from directory
print(loader.locales)
```
--------------------------------
### Send POST Request with Curl
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
Sends a POST request to the /user endpoint with a specified locale ('de_DE') and an empty JSON body. This demonstrates how to interact with the API for localized error messages.
```bash
$ curl -X 'POST' \
'http://127.0.0.1:8000/user?locale=de_DE' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
}'
```
--------------------------------
### Translate Pydantic Validation Errors
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Demonstrates how to use PydanticI18n to translate validation errors for Pydantic models. It shows defining translations, creating an instance of PydanticI18n, and catching and translating ValidationError exceptions.
```python
from decimal import Decimal
from pydantic import BaseModel, Field, ValidationError
from pydantic_i18n import PydanticI18n
# Use {} to mark placeholder positions in translation keys
translations = {
"en_US": {
"Decimal input should have no more than {} in total":
"Decimal input should have no more than {} in total",
"String should have at most {} character":
"String should have at most {} character",
"String should have at most {} characters":
"String should have at most {} characters",
},
"es_AR": {
"Decimal input should have no more than {} in total":
"La entrada decimal no debe tener más de {} en total",
"String should have at most {} character":
"La cadena debe tener como máximo {} carácter",
"String should have at most {} characters":
"La cadena debe tener como máximo {} caracteres",
},
}
tr = PydanticI18n(translations)
class FinancialRecord(BaseModel):
amount: Decimal = Field(max_digits=3)
code: str = Field(max_length=5)
try:
FinancialRecord(amount=12345, code="TOOLONG")
except ValidationError as e:
translated = tr.translate(e.errors(), locale="es_AR")
for error in translated:
print(f"{error['loc']}: {error['msg']}")
# ('amount',): La entrada decimal no debe tener más de 3 digits en total
# ('code',): La cadena debe tener como máximo 5 caracteres
```
--------------------------------
### FastAPI Application with i18n Validation
Source: https://github.com/boardpack/pydantic-i18n/blob/master/docs/en/docs/index.md
A FastAPI application demonstrating the use of pydantic-i18n for internationalized validation error messages. It includes a global dependency for locale and overrides the default validation exception handler.
```Python
from fastapi import FastAPI, Depends
from fastapi.responses import JSONResponse
from pydantic import ValidationError
from tr import User, validation_exception_handler, get_locale
app = FastAPI()
app.dependency_overrides[get_locale] = lambda: "en" # Example: Force English for simplicity
app.add_exception_handler(ValidationError, validation_exception_handler)
@app.post("/user/")
def create_user(user: User):
return user
```
--------------------------------
### Translate Pydantic Validation Errors with PydanticI18n (Python)
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Demonstrates how to use the `PydanticI18n` class to translate Pydantic validation errors into different locales. It shows initialization with a translations dictionary and catching `ValidationError` to translate messages.
```python
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n
# Define translations dictionary with locale -> message mappings
translations = {
"en_US": {
"Field required": "field required",
},
"de_DE": {
"Field required": "Feld erforderlich",
},
"es_AR": {
"Field required": "Campo requerido",
},
}
# Initialize translator with default locale
tr = PydanticI18n(translations, default_locale="en_US")
# Define a Pydantic model
class User(BaseModel):
name: str
email: str
# Catch validation errors and translate them
try:
User() # Missing required fields
except ValidationError as e:
# Translate errors to German
translated_errors = tr.translate(e.errors(), locale="de_DE")
print(translated_errors)
# [
# {
# 'type': 'missing',
# 'loc': ('name',),
# 'msg': 'Feld erforderlich',
# 'input': {},
# 'url': 'https://errors.pydantic.dev/2.6/v/missing'
# },
# {
# 'type': 'missing',
# 'loc': ('email',),
# 'msg': 'Feld erforderlich',
# 'input': {},
# 'url': 'https://errors.pydantic.dev/2.6/v/missing'
# }
# ]
# Access available locales
print(tr.locales) # ('en_US', 'de_DE', 'es_AR')
```
--------------------------------
### FastAPI Integration for Validation Error Translation
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Illustrates how to integrate PydanticI18n with FastAPI to provide localized validation error messages. This involves setting up translation configurations, defining a locale dependency, and implementing a custom exception handler to translate `RequestValidationError`.
```python
from fastapi import Depends, FastAPI, Request
from fastapi.exceptions import RequestValidationError
from starlette.responses import JSONResponse
from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY
from pydantic import BaseModel
from pydantic_i18n import PydanticI18n
# Translation configuration
DEFAULT_LOCALE = "en_US"
translations = {
"en_US": {
"Field required": "field required",
"Input should be a valid integer": "input should be a valid integer",
"Input should be a valid string": "input should be a valid string",
},
"de_DE": {
"Field required": "Feld erforderlich",
"Input should be a valid integer": "Eingabe sollte eine gültige Ganzzahl sein",
"Input should be a valid string": "Eingabe sollte eine gültige Zeichenkette sein",
},
"ja_JP": {
"Field required": "フィールドは必須です",
"Input should be a valid integer": "有効な整数を入力してください",
"Input should be a valid string": "有効な文字列を入力してください",
},
}
tr = PydanticI18n(translations)
# Locale dependency - extracts locale from query params
def get_locale(locale: str = DEFAULT_LOCALE) -> str:
return locale
# Custom exception handler that translates validation errors
async def validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
current_locale = request.query_params.get("locale", DEFAULT_LOCALE)
return JSONResponse(
status_code=HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": tr.translate(exc.errors(), current_locale)},
)
app = FastAPI()
# Add the custom exception handler to the FastAPI app
app.add_exception_handler(RequestValidationError, validation_exception_handler)
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.post("/items/")
async def create_item(item: Item):
return item
```
--------------------------------
### Use DictLoader for In-Memory Pydantic Translations (Python)
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
Illustrates using the `DictLoader` to manage Pydantic translations stored in memory. This loader is implicitly used when a dictionary is passed to `PydanticI18n`, but can also be instantiated explicitly for clarity.
```python
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n, DictLoader
# Define translations with multiple messages per locale
translations = {
"en_US": {
"Field required": "field required",
"Input should be a valid string": "input should be a valid string",
"Input should be a valid integer": "input should be a valid integer",
},
"fr_FR": {
"Field required": "Champ requis",
"Input should be a valid string": "L'entrée doit être une chaîne valide",
"Input should be a valid integer": "L'entrée doit être un entier valide",
},
}
# Create loader explicitly (optional - PydanticI18n does this automatically)
loader = DictLoader(translations)
tr = PydanticI18n(loader)
class Product(BaseModel):
name: str
quantity: int
try:
Product(name=123, quantity="invalid")
except ValidationError as e:
french_errors = tr.translate(e.errors(), locale="fr_FR")
for error in french_errors:
print(f"{error['loc']}: {error['msg']}")
# ('name',): L'entrée doit être une chaîne valide
# ('quantity',): L'entrée doit être un entier valide
```
--------------------------------
### Pydantic Error Translation with Type Search Fallback
Source: https://context7.com/boardpack/pydantic-i18n/llms.txt
This Python snippet shows how to use pydantic-i18n to translate Pydantic validation errors, with a fallback mechanism to search by error type when message translation is not found. It defines translations for 'missing', 'string_type', and 'int_type' in English and German.
```python
from pydantic import BaseModel, ValidationError
from pydantic_i18n import PydanticI18n
# Define translations using error types as keys
translations = {
"en_US": {
"missing": "Field is required",
"string_type": "Must be a string",
"int_type": "Must be an integer",
},
"de_DE": {
"missing": "Feld ist erforderlich",
"string_type": "Muss eine Zeichenkette sein",
"int_type": "Muss eine Ganzzahl sein",
},
}
tr = PydanticI18n(translations, default_locale="en_US")
class Account(BaseModel):
username: str
balance: int
try:
Account(username=123, balance="invalid")
except ValidationError as e:
# Enable type_search to use error type as fallback key
translated = tr.translate(e.errors(), locale="de_DE", type_search=True)
for error in translated:
print(f"{error['type']}: {error['msg']}")
# string_type: Muss eine Zeichenkette sein
# int_type: Muss eine Ganzzahl sein
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.