question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[QUESTION] FASTAPI I18N Internationalization

See original GitHub issue

Hi,

I have database translations. I follow this tutorial to implement in fastapi : https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization.html

my endpoint:

@router.get("/", response_model=List[usrRole])
def read_roles(
    db: Session = Depends(get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: DBUser = Depends(get_current_active_user),
    language: str = Cookie(None),
):

my db_model :

# For testing purposes we define this as simple function which returns
# locale 'fi'. Usually you would define this function as something that
# returns the user's current locale.
def get_locale():
    return 'fi' <<< **how to get language cookie here ....**

translation_hybrid = TranslationHybrid(
    current_locale=get_locale,
    default_locale='en'
)

class usrRole(Base):
    __tablename__  = MODULE_NAME + 'role'
    __table_args__ = ({ "schema": DATABASE_SCHEMA})

    role_id           = Column(Integer,   primary_key=True, index=True)
    name_translations = Column(HSTORE)

    # translated column
    name = translation_hybrid(name_translations)

All works fine but …only with ‘fi’ value 😃 How to get language cookie value in the db_model ?

Regards Frédérik

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

5reactions
KrunchMuffincommented, Sep 10, 2020

Thanks retnikt.

However I find this plugin very useful and FASTAPI users could be interested (at least those using postgreSQL).

After a lot of research I found someone 😃 @https://github.com/omrihar who did a great job of making this plugin work with a middleware ! He gave me his method and in a few minutes I was able to use TranslationHybrid with FASTAPI.

In the same way I could easily communicate the current active user to my audit mixin to update created_by and updated_by table field.

It works perfectly 😃

So I can close this issue.

Be great if you could share with the rest of us. 😃

0reactions
julenbadiolacommented, Feb 9, 2022

My solution:

from contextvars import ContextVar

from sqlalchemy_utils import TranslationHybrid
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request

POSSIBLE_LOCALES = ["en", "es"]
DEFAULT_LOCALE = "en"

_lang: ContextVar[str] = ContextVar(DEFAULT_LOCALE, default=None)


def get_language() -> str:
    return _lang.get()


translation_hybrid = TranslationHybrid(
    current_locale=get_language,
    default_locale=DEFAULT_LOCALE
)


class RequestContextMiddleware(BaseHTTPMiddleware):
    async def dispatch(
        self, request: Request, call_next: RequestResponseEndpoint
    ):
        try:
            lang = request.headers["accept-language"]
            user_language = lang if lang in POSSIBLE_LOCALES else DEFAULT_LOCALE
        except:
            user_language = DEFAULT_LOCALE
        language = _lang.set(user_language)
        response = await call_next(request)
        return response

Add the middleware to the fastapi app

app.add_middleware(RequestContextMiddleware)
Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI I18n Step by Step | Phrase
Looking for ways to internationalize your FastAPI application using Python libraries? Our step-by-step FastAPI i18n tutorial can help!
Read more >
python - fastapi-localization is not translating my API response
I have installed and implemented fastapi-localization just ...
Read more >
Easy way to internationalize your apps with PyI18n
PyI18n is a simple and easy to use internationalization library written for ... Dict app: FastAPI = FastAPI() i18n: PyI18n = PyI18n(('pl', ...
Read more >
fastapi-localization - PyPI
fastapi_localization - provides a simple language localization from Accept-Language header in your application. Installation $ pip install fastapi- ...
Read more >
Help FastAPI - Get Help
First, make sure you understand the problem that the pull request is trying to solve. It might have a longer discussion in an...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found