Anbarryprojects / fastapi-babel

FastAPI babel support pybable tools like translation of text, formatting of dates, times and numbers, and time zones.
MIT License
46 stars 14 forks source link

Locale languages not evaluated correctly from Accept-Language header #19

Closed gjedlicska closed 4 months ago

gjedlicska commented 1 year ago

I'm using the fastapi jinja2 example and I'm facing an issue with locale code resolving.

I have 2 locales, en the default one, and hu. Both are initialized according to the docs, and they both contain the proper messages files in lang/{locale}/LC_MESSAGES/messages.po | .mo

When my browser (OSX Firefox and Safari) sends the Accept-Language header, it sends a value 'en-US,en;q=0.7,hu;q=0.3' which I was expecting to resolve to the en localization folder.

But the request fails with:

FileNotFoundError: [Errno 2] No translation file found for domain: 'messages'

gettext tries to look for the translation file: {ROOT_DIR}/lang/en-US,en;q=0/LC_MESSAGES/messages.mo

The ROOT_DIR is properly configured, the issue is caused by the mismatch in the language specific subdirectory. If I rename the en folder to en-US,en;q=0 the translation is properly found.

Legopapurida commented 1 year ago

Thanks for mentioning this error I will take over this issue and release a new version.

Legopapurida commented 1 year ago

We added a new release and I hope this issue solved as well.

Legopapurida commented 1 year ago

For your problem, I recommend separating the URL path of locales such as this Hu locale: https://{domain}.com/hu/login En locale: https://{domain}.com/en/login

and create a dependency in fastapi to change babel.locale from the path parameter, and this will translate automatically. because each browser has its own particular accept-language header value and recognition between them is a bit hard either your website is templating you must split the translation from the URL path instead of the request header. but if you are using a restful architect I offer you to use of the request header.

gjedlicska commented 1 year ago

Thank you for the response, im going to give the new release a try.

awilhelm-projects commented 7 months ago

Can you please update PIP Package! This error comes every time.

AnderUstarroz commented 4 months ago

This issue will also be solved after merging the Pull request mentioned here and making a new release v0.0.9.