Add user locale preference support and locale detection logic

- Introduced `locale` field in user model and schemas with BCP 47 format validation.
- Created Alembic migration to add `locale` column to the `users` table with indexing for better query performance.
- Implemented `get_locale` dependency to detect locale using user preference, `Accept-Language` header, or default to English.
- Added extensive tests for locale validation, dependency logic, and fallback handling.
- Enhanced documentation and comments detailing the locale detection workflow and SUPPORTED_LOCALES configuration.
This commit is contained in:
Felipe Cardoso
2025-11-17 19:47:50 +01:00
parent 3001484948
commit 68e04a911a
6 changed files with 665 additions and 1 deletions

View File

@@ -0,0 +1,42 @@
"""add user locale preference column
Revision ID: c8e9f3a2d1b4
Revises: b76c725fc3cf
Create Date: 2025-11-17 18:00:00.000000
"""
from collections.abc import Sequence
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision: str = "c8e9f3a2d1b4"
down_revision: str | None = "b76c725fc3cf"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None
def upgrade() -> None:
# Add locale column to users table
# VARCHAR(10) supports BCP 47 format (e.g., "en", "it", "en-US", "it-IT")
# Nullable: NULL means "not set yet", will use Accept-Language header fallback
# Indexed: For analytics queries and filtering by locale
op.add_column(
"users",
sa.Column("locale", sa.String(length=10), nullable=True)
)
# Create index on locale column for performance
op.create_index(
"ix_users_locale",
"users",
["locale"],
)
def downgrade() -> None:
# Remove locale index and column
op.drop_index("ix_users_locale", table_name="users")
op.drop_column("users", "locale")