.\" Man page generated from reStructuredText. . . .nr rst2man-indent-level 0 . .de1 rstReportMargin \\$1 \\n[an-margin] level \\n[rst2man-indent-level] level margin: \\n[rst2man-indent\\n[rst2man-indent-level]] - \\n[rst2man-indent0] \\n[rst2man-indent1] \\n[rst2man-indent2] .. .de1 INDENT .\" .rstReportMargin pre: . RS \\$1 . nr rst2man-indent\\n[rst2man-indent-level] \\n[an-margin] . nr rst2man-indent-level +1 .\" .rstReportMargin post: .. .de UNINDENT . RE .\" indent \\n[an-margin] .\" old: \\n[rst2man-indent\\n[rst2man-indent-level]] .nr rst2man-indent-level -1 .\" new: \\n[rst2man-indent\\n[rst2man-indent-level]] .in \\n[rst2man-indent\\n[rst2man-indent-level]]u .. .TH "FLASKBABEL" "1" "Apr 06, 2024" "1.0" "Flask Babel" .SH NAME flaskbabel \- Flask Babel Documentation .sp Flask\-BabelEx is an extension to \fI\%Flask\fP that adds i18n and l10n support to any Flask application with the help of \fI\%babel\fP, \fI\%pytz\fP and \fI\%speaklater\fP\&. It has builtin support for date formatting with timezone support as well as a very simple and friendly interface to \fI\%gettext\fP translations. .SH INSTALLATION .sp Install the extension with one of the following commands: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ easy_install Flask\-BabelEx .ft P .fi .UNINDENT .UNINDENT .sp or alternatively if you have pip installed: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pip install Flask\-BabelEx .ft P .fi .UNINDENT .UNINDENT .sp Please note that Flask\-BabelEx requires Jinja 2.5. If you are using an older version you will have to upgrade or disable the Jinja support. .SH CONFIGURATION .sp To get started all you need to do is to instanciate a \fI\%Babel\fP object after configuring the application: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask import Flask from flask_babelex import Babel app = Flask(__name__) app.config.from_pyfile(\(aqmysettings.cfg\(aq) babel = Babel(app) .ft P .fi .UNINDENT .UNINDENT .sp The babel object itself can be used to configure the babel support further. Babel has two configuration values that can be used to change some internal defaults: .TS center; |l|l|. _ T{ \fIBABEL_DEFAULT_LOCALE\fP T} T{ The default locale to use if no locale selector is registered. This defaults to \fB\(aqen\(aq\fP\&. T} _ T{ \fIBABEL_DEFAULT_TIMEZONE\fP T} T{ The timezone to use for user facing dates. This defaults to \fB\(aqUTC\(aq\fP which also is the timezone your application must use internally. T} _ .TE .sp For more complex applications you might want to have multiple applications for different users which is where selector functions come in handy. The first time the babel extension needs the locale (language code) of the current user it will call a \fI\%localeselector()\fP function, and the first time the timezone is needed it will call a \fI\%timezoneselector()\fP function. .sp If any of these methods return \fINone\fP the extension will automatically fall back to what\(aqs in the config. Furthermore for efficiency that function is called only once and the return value then cached. If you need to switch the language between a request, you can \fI\%refresh()\fP the cache. .sp Example selector functions: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask import g, request @babel.localeselector def get_locale(): # if a user is logged in, use the locale from the user settings user = getattr(g, \(aquser\(aq, None) if user is not None: return user.locale # otherwise try to guess the language from the user accept # header the browser transmits. We support de/fr/en in this # example. The best match wins. return request.accept_languages.best_match([\(aqde\(aq, \(aqfr\(aq, \(aqen\(aq]) @babel.timezoneselector def get_timezone(): user = getattr(g, \(aquser\(aq, None) if user is not None: return user.timezone .ft P .fi .UNINDENT .UNINDENT .sp The example above assumes that the current user is stored on the \fI\%flask.g\fP object. .SH FORMATTING DATES .sp To format dates you can use the \fI\%format_datetime()\fP, \fI\%format_date()\fP, \fI\%format_time()\fP and \fI\%format_timedelta()\fP functions. They all accept a \fI\%datetime.datetime\fP (or \fI\%datetime.date\fP, \fI\%datetime.time\fP and \fI\%datetime.timedelta\fP) object as first parameter and then optionally a format string. The application should use naive datetime objects internally that use UTC as timezone. On formatting it will automatically convert into the user\(aqs timezone in case it differs from UTC. .sp To play with the date formatting from the console, you can use the \fI\%test_request_context()\fP method: .sp .nf .ft C >>> app.test_request_context().push() .ft P .fi .sp Here some examples: .sp .nf .ft C >>> from flask_babelex import format_datetime >>> from datetime import datetime >>> format_datetime(datetime(1987, 3, 5, 17, 12)) u\(aqMar 5, 1987 5:12:00 PM\(aq >>> format_datetime(datetime(1987, 3, 5, 17, 12), \(aqfull\(aq) u\(aqThursday, March 5, 1987 5:12:00 PM World (GMT) Time\(aq >>> format_datetime(datetime(1987, 3, 5, 17, 12), \(aqshort\(aq) u\(aq3/5/87 5:12 PM\(aq >>> format_datetime(datetime(1987, 3, 5, 17, 12), \(aqdd mm yyy\(aq) u\(aq05 12 1987\(aq >>> format_datetime(datetime(1987, 3, 5, 17, 12), \(aqdd mm yyyy\(aq) u\(aq05 12 1987\(aq .ft P .fi .sp And again with a different language: .sp .nf .ft C >>> app.config[\(aqBABEL_DEFAULT_LOCALE\(aq] = \(aqde\(aq >>> from flask_babelex import refresh; refresh() >>> format_datetime(datetime(1987, 3, 5, 17, 12), \(aqEEEE, d. MMMM yyyy H:mm\(aq) u\(aqDonnerstag, 5. M\exe4rz 1987 17:12\(aq .ft P .fi .sp For more format examples head over to the \fI\%babel\fP documentation. .SH USING TRANSLATIONS .sp The other big part next to date formatting are translations. For that, Flask uses \fI\%gettext\fP together with Babel. The idea of gettext is that you can mark certain strings as translatable and a tool will pick all those app, collect them in a separate file for you to translate. At runtime the original strings (which should be English) will be replaced by the language you selected. .sp There are two functions responsible for translating: \fI\%gettext()\fP and \fI\%ngettext()\fP\&. The first to translate singular strings and the second to translate strings that might become plural. Here some examples: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask_babelex import gettext, ngettext gettext(u\(aqA simple string\(aq) gettext(u\(aqValue: %(value)s\(aq, value=42) ngettext(u\(aq%(num)s Apple\(aq, u\(aq%(num)s Apples\(aq, number_of_apples) .ft P .fi .UNINDENT .UNINDENT .sp Additionally if you want to use constant strings somewhere in your application and define them outside of a request, you can use a lazy strings. Lazy strings will not be evaluated until they are actually used. To use such a lazy string, use the \fI\%lazy_gettext()\fP function: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask_babelex import lazy_gettext class MyForm(formlibrary.FormBase): success_message = lazy_gettext(u\(aqThe form was successfully saved.\(aq) .ft P .fi .UNINDENT .UNINDENT .sp So how does Flask\-BabelEx find the translations? Well first you have to create some. Here is how you do it: .SH TRANSLATING APPLICATIONS .sp First you need to mark all the strings you want to translate in your application with \fI\%gettext()\fP or \fI\%ngettext()\fP\&. After that, it\(aqs time to create a \fB\&.pot\fP file. A \fB\&.pot\fP file contains all the strings and is the template for a \fB\&.po\fP file which contains the translated strings. Babel can do all that for you. .sp First of all you have to get into the folder where you have your application and create a mapping file. For typical Flask applications, this is what you want in there: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C [python: **.py] [jinja2: **/templates/**.html] extensions=jinja2.ext.autoescape,jinja2.ext.with_ .ft P .fi .UNINDENT .UNINDENT .sp Save it as \fBbabel.cfg\fP or something similar next to your application. Then it\(aqs time to run the \fIpybabel\fP command that comes with Babel to extract your strings: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pybabel extract \-F babel.cfg \-o messages.pot . .ft P .fi .UNINDENT .UNINDENT .sp If you are using the \fI\%lazy_gettext()\fP function you should tell pybabel that it should also look for such function calls: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pybabel extract \-F babel.cfg \-k lazy_gettext \-o messages.pot . .ft P .fi .UNINDENT .UNINDENT .sp This will use the mapping from the \fBbabel.cfg\fP file and store the generated template in \fBmessages.pot\fP\&. Now we can create the first translation. For example to translate to German use this command: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pybabel init \-i messages.pot \-d translations \-l de .ft P .fi .UNINDENT .UNINDENT .sp \fB\-d translations\fP tells pybabel to store the translations in this folder. This is where Flask\-BabelEx will look for translations. Put it next to your template folder. .sp Now edit the \fBtranslations/de/LC_MESSAGES/messages.po\fP file as needed. Check out some gettext tutorials if you feel lost. .sp To compile the translations for use, \fBpybabel\fP helps again: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pybabel compile \-d translations .ft P .fi .UNINDENT .UNINDENT .sp What if the strings change? Create a new \fBmessages.pot\fP like above and then let \fBpybabel\fP merge the changes: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ pybabel update \-i messages.pot \-d translations .ft P .fi .UNINDENT .UNINDENT .sp Afterwards some strings might be marked as fuzzy (where it tried to figure out if a translation matched a changed key). If you have fuzzy entries, make sure to check them by hand and remove the fuzzy flag before compiling. .sp Flask\-BabelEx looks for message catalogs in \fBtranslations\fP directory which should be located under Flask application directory. Default domain is \(dqmessages\(dq. .sp For example, if you want to have translations for German, Spanish and French, directory structure should look like this: .INDENT 0.0 .INDENT 3.5 translations/de/LC_MESSAGES/messages.mo translations/sp/LC_MESSAGES/messages.mo translations/fr/LC_MESSAGES/messages.mo .UNINDENT .UNINDENT .SH TRANSLATION DOMAINS .sp By default, Flask\-BabelEx will use \(dqmessages\(dq domain, which will make it use translations from the \fBmessages.mo\fP file. It is not very convenient for third\-party Flask extensions, which might want to localize themselves without requiring user to merge their translations into \(dqmessages\(dq domain. .sp Flask\-BabelEx allows extension developers to specify which translation domain to use: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask_babelex import Domain mydomain = Domain(domain=\(aqmyext\(aq) mydomain.lazy_gettext(\(aqHello World!\(aq) .ft P .fi .UNINDENT .UNINDENT .sp \fI\%Domain\fP contains all gettext\-related methods (\fI\%gettext()\fP, \fI\%ngettext()\fP, etc). .sp In previous example, localizations will be read from the \fBmyext.mo\fP files, but they have to be located in \fBtranslations\fP directory under users Flask application. If extension is distributed with the localizations, it is possible to specify their location: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask_babelex import Domain from flask.ext.myext import translations mydomain = Domain(translations.__path__[0]) .ft P .fi .UNINDENT .UNINDENT .sp \fBmydomain\fP will look for translations in extension directory with default (messages) domain. .sp It is also possible to change the translation domain used by default, either for each app or per request. .sp To set the \fI\%Domain\fP that will be used in an app, pass it to \fI\%Babel\fP on initialization: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask import Flask from flask_babelex import Babel, Domain app = Flask(__name__) domain = Domain(domain=\(aqmyext\(aq) babel = Babel(app, default_domain=domain) .ft P .fi .UNINDENT .UNINDENT .sp Translations will then come from the \fBmyext.mo\fP files by default. .sp To change the default domain in a request context, call the \fI\%as_default()\fP method from within the request context: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C from flask import Flask from flask_babelex import Babel, Domain, gettext app = Flask(__name__) domain = Domain(domain=\(aqmyext\(aq) babel = Babel(app) @app.route(\(aq/path\(aq) def demopage(): domain.as_default() return gettext(\(aqHello World!\(aq) .ft P .fi .UNINDENT .UNINDENT .sp \fBHello World!\fP will get translated using the \fBmyext.mo\fP files, but other requests will use the default \fBmessages.mo\fP\&. Note that a \fI\%Babel\fP must be initialized for the app for translations to work at all. .SH TROUBLESHOOTING .sp On Snow Leopard pybabel will most likely fail with an exception. If this happens, check if this command outputs UTF\-8: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C $ echo $LC_CTYPE UTF\-8 .ft P .fi .UNINDENT .UNINDENT .sp This is a OS X bug unfortunately. To fix it, put the following lines into your \fB~/.profile\fP file: .INDENT 0.0 .INDENT 3.5 .sp .nf .ft C export LC_CTYPE=en_US.utf\-8 .ft P .fi .UNINDENT .UNINDENT .sp Then restart your terminal. .SH API .sp This part of the documentation documents each and every public class or function from Flask\-BabelEx. .SS Configuration .INDENT 0.0 .TP .B class flask_babelex.Babel(app=None, default_locale=\(aqen\(aq, default_timezone=\(aqUTC\(aq, date_formats=None, configure_jinja=True, default_domain=None) Central controller class that can be used to configure how Flask\-Babel behaves. Each application that wants to use Flask\-Babel has to create, or run \fI\%init_app()\fP on, an instance of this class after the configuration was initialized. .INDENT 7.0 .TP .B property default_locale The default locale from the configuration as instance of a \fIbabel.Locale\fP object. .UNINDENT .INDENT 7.0 .TP .B property default_timezone The default timezone from the configuration as instance of a \fIpytz.timezone\fP object. .UNINDENT .INDENT 7.0 .TP .B init_app(app) Set up this instance for use with \fIapp\fP, if no app was passed to the constructor. .UNINDENT .INDENT 7.0 .TP .B list_translations() Returns a list of all the locales translations exist for. The list returned will be filled with actual locale objects and not just strings. .sp New in version 0.6. .UNINDENT .INDENT 7.0 .TP .B load_locale(locale) Load locale by name and cache it. Returns instance of a \fIbabel.Locale\fP object. .UNINDENT .INDENT 7.0 .TP .B localeselector(f) Registers a callback function for locale selection. The default behaves as if a function was registered that returns \fINone\fP all the time. If \fINone\fP is returned, the locale falls back to the one from the configuration. .sp This has to return the locale as string (eg: \fB\(aqde_AT\(aq\fP, \(aq\(aq\fIen_US\fP\(aq\(aq) .UNINDENT .INDENT 7.0 .TP .B timezoneselector(f) Registers a callback function for timezone selection. The default behaves as if a function was registered that returns \fINone\fP all the time. If \fINone\fP is returned, the timezone falls back to the one from the configuration. .sp This has to return the timezone as string (eg: \fB\(aqEurope/Vienna\(aq\fP) .UNINDENT .UNINDENT .SS Context Functions .INDENT 0.0 .TP .B flask_babelex.get_locale() Returns the locale that should be used for this request as \fIbabel.Locale\fP object. This returns \fINone\fP if used outside of a request. If flask\-babel was not attached to the Flask application, will return \(aqen\(aq locale. .UNINDENT .INDENT 0.0 .TP .B flask_babelex.get_timezone() Returns the timezone that should be used for this request as \fIpytz.timezone\fP object. This returns \fINone\fP if used outside of a request. If flask\-babel was not attached to application, will return UTC timezone object. .UNINDENT .SS Translation domains .INDENT 0.0 .TP .B class flask_babelex.Domain(dirname=None, domain=\(aqmessages\(aq) Localization domain. By default will use look for tranlations in Flask application directory and \(dqmessages\(dq domain \- all message catalogs should be called \fBmessages.mo\fP\&. .INDENT 7.0 .TP .B as_default() Set this domain as default for the current request .UNINDENT .INDENT 7.0 .TP .B get_translations() Returns the correct gettext translations that should be used for this request. This will never fail and return a dummy translation object if used outside of the request or if a translation cannot be found. .UNINDENT .INDENT 7.0 .TP .B get_translations_cache(ctx) Returns dictionary\-like object for translation caching .UNINDENT .INDENT 7.0 .TP .B get_translations_path(ctx) Returns translations directory path. Override if you want to implement custom behavior. .UNINDENT .INDENT 7.0 .TP .B gettext(string, **variables) Translates a string with the current locale and passes in the given keyword arguments as mapping to a string formatting string. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C gettext(u\(aqHello World!\(aq) gettext(u\(aqHello %(name)s!\(aq, name=\(aqWorld\(aq) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B lazy_gettext(string, **variables) Like \fI\%gettext()\fP but the string returned is lazy which means it will be translated when it is used as an actual string. .sp Example: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C hello = lazy_gettext(u\(aqHello World\(aq) @app.route(\(aq/\(aq) def index(): return unicode(hello) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B lazy_pgettext(context, string, **variables) Like \fI\%pgettext()\fP but the string returned is lazy which means it will be translated when it is used as an actual string. .sp New in version 0.7. .UNINDENT .INDENT 7.0 .TP .B ngettext(singular, plural, num, **variables) Translates a string with the current locale and passes in the given keyword arguments as mapping to a string formatting string. The \fInum\fP parameter is used to dispatch between singular and various plural forms of the message. It is available in the format string as \fB%(num)d\fP or \fB%(num)s\fP\&. The source language should be English or a similar language which only has one plural form. .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C ngettext(u\(aq%(num)d Apple\(aq, u\(aq%(num)d Apples\(aq, num=len(apples)) .ft P .fi .UNINDENT .UNINDENT .UNINDENT .INDENT 7.0 .TP .B npgettext(context, singular, plural, num, **variables) Like \fI\%ngettext()\fP but with a context. .sp New in version 0.7. .UNINDENT .INDENT 7.0 .TP .B pgettext(context, string, **variables) Like \fI\%gettext()\fP but with a context. .sp New in version 0.7. .UNINDENT .UNINDENT .SS Datetime Functions .INDENT 0.0 .TP .B flask_babelex.to_user_timezone(datetime) Convert a datetime object to the user\(aqs timezone. This automatically happens on all date formatting unless rebasing is disabled. If you need to convert a \fI\%datetime.datetime\fP object at any time to the user\(aqs timezone (as returned by \fI\%get_timezone()\fP this function can be used). .UNINDENT .INDENT 0.0 .TP .B flask_babelex.to_utc(datetime) Convert a datetime object to UTC and drop tzinfo. This is the opposite operation to \fI\%to_user_timezone()\fP\&. .UNINDENT .INDENT 0.0 .TP .B flask_babelex.format_datetime(datetime=None, format=None, rebase=True) Return a date formatted according to the given pattern. If no \fI\%datetime\fP object is passed, the current time is assumed. By default rebasing happens which causes the object to be converted to the users\(aqs timezone (as returned by \fI\%to_user_timezone()\fP). This function formats both date and time. .sp The format parameter can either be \fB\(aqshort\(aq\fP, \fB\(aqmedium\(aq\fP, \fB\(aqlong\(aq\fP or \fB\(aqfull\(aq\fP (in which cause the language\(aqs default for that setting is used, or the default from the \fBBabel.date_formats\fP mapping is used) or a format string as documented by Babel. .sp This function is also available in the template context as filter named \fIdatetimeformat\fP\&. .UNINDENT .INDENT 0.0 .TP .B flask_babelex.format_date(date=None, format=None, rebase=True) Return a date formatted according to the given pattern. If no \fI\%datetime\fP or \fI\%date\fP object is passed, the current time is assumed. By default rebasing happens which causes the object to be converted to the users\(aqs timezone (as returned by \fI\%to_user_timezone()\fP). This function only formats the date part of a \fI\%datetime\fP object. .sp The format parameter can either be \fB\(aqshort\(aq\fP, \fB\(aqmedium\(aq\fP, \fB\(aqlong\(aq\fP or \fB\(aqfull\(aq\fP (in which cause the language\(aqs default for that setting is used, or the default from the \fBBabel.date_formats\fP mapping is used) or a format string as documented by Babel. .sp This function is also available in the template context as filter named \fIdateformat\fP\&. .UNINDENT .INDENT 0.0 .TP .B flask_babelex.format_time(time=None, format=None, rebase=True) Return a time formatted according to the given pattern. If no \fI\%datetime\fP object is passed, the current time is assumed. By default rebasing happens which causes the object to be converted to the users\(aqs timezone (as returned by \fI\%to_user_timezone()\fP). This function formats both date and time. .sp The format parameter can either be \fB\(aqshort\(aq\fP, \fB\(aqmedium\(aq\fP, \fB\(aqlong\(aq\fP or \fB\(aqfull\(aq\fP (in which cause the language\(aqs default for that setting is used, or the default from the \fBBabel.date_formats\fP mapping is used) or a format string as documented by Babel. .sp This function is also available in the template context as filter named \fItimeformat\fP\&. .UNINDENT .INDENT 0.0 .TP .B flask_babelex.format_timedelta(datetime_or_timedelta, granularity=\(aqsecond\(aq) Format the elapsed time from the given date to now or the given timedelta. This currently requires an unreleased development version of Babel. .sp This function is also available in the template context as filter named \fItimedeltaformat\fP\&. .UNINDENT .SS Gettext Functions .INDENT 0.0 .TP .B flask_babelex.gettext(*args, **kwargs) .UNINDENT .INDENT 0.0 .TP .B flask_babelex.ngettext(*args, **kwargs) .UNINDENT .INDENT 0.0 .TP .B flask_babelex.pgettext(*args, **kwargs) .UNINDENT .INDENT 0.0 .TP .B flask_babelex.npgettext(*args, **kwargs) .UNINDENT .INDENT 0.0 .TP .B flask_babelex.lazy_gettext(*args, **kwargs) .UNINDENT .INDENT 0.0 .TP .B flask_babelex.lazy_pgettext(*args, **kwargs) .UNINDENT .SS Low\-Level API .INDENT 0.0 .TP .B flask_babelex.refresh() Refreshes the cached timezones and locale information. This can be used to switch a translation between a request and if you want the changes to take place immediately, not just with the next request: .INDENT 7.0 .INDENT 3.5 .sp .nf .ft C user.timezone = request.form[\(aqtimezone\(aq] user.locale = request.form[\(aqlocale\(aq] refresh() flash(gettext(\(aqLanguage was changed\(aq)) .ft P .fi .UNINDENT .UNINDENT .sp Without that refresh, the \fI\%flash()\fP function would probably return English text and a now German page. .UNINDENT .SH AUTHOR Armin Ronacher .SH COPYRIGHT 2024, Armin Ronacher .\" Generated by docutils manpage writer. .