Flask-Babel 使用示例

下面創建一個簡單的 Flask-Babel 示例,展示如何在 Flask 應用中實現國際化和本地化功能。這個示例將包括多語言支持(中文和英文)、語言切換功能以及翻譯文本的使用。

項目結構

我們將創建以下文件結構:
在這里插入圖片描述

1. 首先,創建 requirements.txt 文件

flask==2.3.3
flask-babel==3.1.0

項目構建:
在這里插入圖片描述

2. 創建配置文件

import osclass Config:# 設置密鑰SECRET_KEY = os.environ.get('SECRET_KEY') or 'dev-key-should-be-changed'# Babel 配置LANGUAGES = ['en', 'zh']BABEL_DEFAULT_LOCALE = 'en'BABEL_DEFAULT_TIMEZONE = 'UTC'

3. 創建 Babel 配置文件

[python: **.py]
[jinja2: **/templates/**.html]

4. 創建 HTML 模板

基礎模板

<!DOCTYPE html>
<html lang="{{ g.locale }}">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{% block title %}{{ _('Flask Babel Example') }}{% endblock %}</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css"><style>body { padding-top: 20px; }.content { margin-top: 20px; }.language-selector { margin-top: 10px; }</style>
</head>
<body><div class="container"><nav class="navbar navbar-expand-lg navbar-light bg-light"><div class="container-fluid"><a class="navbar-brand" href="{{ url_for('index') }}">{{ _('Flask Babel') }}</a><div class="language-selector"><a href="{{ url_for('set_locale', locale='en') }}" class="btn btn-sm {% if g.locale == 'en' %}btn-primary{% else %}btn-outline-primary{% endif %}">English</a><a href="{{ url_for('set_locale', locale='zh') }}" class="btn btn-sm {% if g.locale == 'zh' %}btn-primary{% else %}btn-outline-primary{% endif %}">中文</a></div></div></nav><div class="content">{% block content %}{% endblock %}</div></div><script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

首頁模板

{% extends "base.html" %}{% block title %}{{ _('Home') }} - {{ _('Flask Babel Example') }}{% endblock %}{% block content %}
<div class="jumbotron"><h1 class="display-4">{{ _('Welcome to Flask Babel Example') }}</h1><p class="lead">{{ _('This is a simple demonstration of Flask-Babel for internationalization.') }}</p><hr class="my-4"><p>{{ _('Current language') }}: <strong>{{ g.locale }}</strong></p><p>{{ _('Current time') }}: {{ moment }}</p><p>{{ _('Sample translated text with parameters: Hello, %(name)s!', name='Flask') }}</p><h3>{{ _('Features demonstrated:') }}</h3><ul><li>{{ _('Text translation with gettext') }}</li><li>{{ _('Language switching') }}</li><li>{{ _('Date and time localization') }}</li><li>{{ _('Parameter substitution in translations') }}</li></ul>
</div>
{% endblock %}

5. 創建主應用文件

from flask import Flask, render_template, request, g, session, redirect, url_for
from flask_babel import Babel, gettext, format_datetime
from datetime import datetime
import os
from config import Configapp = Flask(__name__)
app.config.from_object(Config)# 定義選擇器函數
def get_locale():# 如果用戶已經選擇了語言,則使用用戶選擇的語言if 'locale' in session:return session['locale']# 否則,嘗試從請求頭中獲取最佳匹配的語言return request.accept_languages.best_match(app.config['LANGUAGES'])def get_timezone():# 這里可以根據用戶設置返回不同的時區return app.config['BABEL_DEFAULT_TIMEZONE']# 初始化 Babel(使用新版本 API)
babel = Babel(app, locale_selector=get_locale, timezone_selector=get_timezone)@app.before_request
def before_request():g.locale = get_locale()@app.route('/')
def index():# 獲取當前時間并格式化moment = format_datetime(datetime.utcnow())return render_template('index.html', moment=moment)@app.route('/set_locale/<locale>')
def set_locale(locale):# 檢查是否是支持的語言if locale in app.config['LANGUAGES']:session['locale'] = localereturn redirect(url_for('index'))if __name__ == '__main__':# 確保 translations 目錄存在if not os.path.exists('translations'):os.makedirs('translations')app.run(debug=True)

6. 創建翻譯文件

首先,我們需要提取需要翻譯的文本:

pybabel extract -F babel.cfg -o messages.pot .

然后,為每種語言創建翻譯文件:

# 創建英文翻譯文件
pybabel init -i messages.pot -d translations -l en# 創建中文翻譯文件
pybabel init -i messages.pot -d translations -l zh

編輯翻譯文件:

英文翻譯文件 (translations/en/LC_MESSAGES/messages.po)

# English translations for PROJECT.
# Copyright (C) 2025 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2025-06-05 22:01+0800\n"
"PO-Revision-Date: 2025-06-05 22:02+0800\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: en\n"
"Language-Team: en <LL@li.org>\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.17.0\n"#: templates/base.html:6 templates/index.html:3
msgid "Flask Babel Example"
msgstr "Flask Babel Example"#: templates/base.html:18
msgid "Flask Babel"
msgstr "Flask Babel"#: templates/index.html:3
msgid "Home"
msgstr "Home"#: templates/index.html:7
msgid "Welcome to Flask Babel Example"
msgstr "Welcome to Flask Babel Example"#: templates/index.html:8
msgid "This is a simple demonstration of Flask-Babel for internationalization."
msgstr "This is a simple demonstration of Flask-Babel for internationalization."#: templates/index.html:10
msgid "Current language"
msgstr "Current language"#: templates/index.html:11
msgid "Current time"
msgstr "Current time"#: templates/index.html:12
#, python-format
msgid "Sample translated text with parameters: Hello, %(name)s!"
msgstr "Sample translated text with parameters: Hello, %(name)s!"#: templates/index.html:14
msgid "Features demonstrated:"
msgstr "Features demonstrated:"#: templates/index.html:16
msgid "Text translation with gettext"
msgstr "Text translation with gettext"#: templates/index.html:17
msgid "Language switching"
msgstr "Language switching"#: templates/index.html:18
msgid "Date and time localization"
msgstr "Date and time localization"#: templates/index.html:19
msgid "Parameter substitution in translations"
msgstr "Parameter substitution in translations"

中文翻譯文件 (translations/zh/LC_MESSAGES/messages.po)

# Chinese translations for PROJECT.
# Copyright (C) 2025 ORGANIZATION
# This file is distributed under the same license as the PROJECT project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2025-06-05 22:01+0800\n"
"PO-Revision-Date: 2025-06-05 22:02+0800\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: zh\n"
"Language-Team: zh <LL@li.org>\n"
"Plural-Forms: nplurals=1; plural=0;\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.17.0\n"#: templates/base.html:6 templates/index.html:3
msgid "Flask Babel Example"
msgstr "Flask Babel 示例"#: templates/base.html:18
msgid "Flask Babel"
msgstr "Flask Babel"#: templates/index.html:3
msgid "Home"
msgstr "首頁"#: templates/index.html:7
msgid "Welcome to Flask Babel Example"
msgstr "歡迎使用 Flask Babel 示例"#: templates/index.html:8
msgid "This is a simple demonstration of Flask-Babel for internationalization."
msgstr "這是一個簡單的 Flask-Babel 國際化演示。"#: templates/index.html:10
msgid "Current language"
msgstr "當前語言"#: templates/index.html:11
msgid "Current time"
msgstr "當前時間"#: templates/index.html:12
#, python-format
msgid "Sample translated text with parameters: Hello, %(name)s!"
msgstr "帶參數的示例翻譯文本:你好,%(name)s!"#: templates/index.html:14
msgid "Features demonstrated:"
msgstr "演示的功能:"#: templates/index.html:16
msgid "Text translation with gettext"
msgstr "使用 gettext 進行文本翻譯"#: templates/index.html:17
msgid "Language switching"
msgstr "語言切換"#: templates/index.html:18
msgid "Date and time localization"
msgstr "日期和時間本地化"#: templates/index.html:19
msgid "Parameter substitution in translations"
msgstr "翻譯中的參數替換"

編輯完翻譯文件后,需要編譯它們:

pybabel compile -d translations

運行應用

uv run app.py

應用將在 http://127.0.0.1:5000/ 上運行。
在這里插入圖片描述
切換英文
在這里插入圖片描述

功能說明

  1. 多語言支持:應用支持英文和中文兩種語言。
  2. 語言切換:用戶可以通過點擊頁面頂部的語言按鈕切換語言。
  3. 文本翻譯:使用 gettext 函數(在模板中使用 _() 簡寫)來標記需要翻譯的文本。
  4. 日期和時間本地化:使用 format_datetime 函數根據當前語言環境格式化日期和時間。
  5. 參數替換:在翻譯文本中使用參數,例如 _('Hello, %(name)s!', name='Flask')

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/85811.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/85811.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/85811.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

[論文閱讀] 軟件工程 | 量子計算如何賦能軟件工程(Quantum-Based Software Engineering)

arXiv:2505.23674 [pdf, html, other] Quantum-Based Software Engineering Jianjun Zhao Subjects: Software Engineering (cs.SE); Quantum Physics (quant-ph) 量子計算如何賦能軟件工程 我們在開發軟件時&#xff0c;常常會遇到一些棘手的問題。比如&#xff0c;為了確保軟…

Ansible 進階 - Roles 與 Inventory 的高效組織

Ansible 進階 - Roles 與 Inventory 的高效組織 如果說 Playbook 是一份完整的“菜譜”,那么 Role (角色) 就可以被看作是制作這道菜(或一桌菜)所需的標準化“備料包”或“半成品組件”。例如,我們可以有一個“Nginx Web 服務器安裝配置 Role”、“MySQL 數據庫基礎設置 Ro…

青少年編程與數學 01-011 系統軟件簡介 04 Linux操作系統

青少年編程與數學 01-011 系統軟件簡介 04 Linux操作系統 一、Linux 的發展歷程&#xff08;一&#xff09;起源&#xff08;二&#xff09;早期發展&#xff08;三&#xff09;成熟與普及&#xff08;四&#xff09;移動與嵌入式領域的拓展 二、Linux 的內核與架構&#xff08…

將圖形可視化工具的 Python 腳本打包為 Windows 應用程序

前文我們已經寫了一個基于python的tkinter庫和matplotlib庫的圖形可視化工具。 基于Python的tkinter庫的圖形可視化工具&#xff08;15種圖形的完整代碼&#xff09;:基于Python的tkinter庫的圖形可視化工具&#xff08;15種圖形的完整代碼&#xff09;-CSDN博客 在前文基礎上&…

【Kotlin】簡介變量類接口

【Kotlin】簡介&變量&類&接口 【Kotlin】數字&字符串&數組&集合 【Kotlin】高階函數&Lambda&內聯函數 【Kotlin】表達式&關鍵字 文章目錄 Kotlin_簡介&變量&類&接口Kotlin的特性Kotlin優勢創建Kotlin項目變量變量保存了指向對…

OpenCV種的cv::Mat與Qt種的QImage類型相互轉換

一、首先了解cv::Mat結構體 cv::Mat::step與QImage轉換有著較大的關系。 step的幾個類別區分: step:矩陣第一行元素的字節數step[0]:矩陣第一行元素的字節數step[1]:矩陣中一個元素的字節數step1(0):矩陣中一行有幾個通道數step1(1):一個元素有幾個通道數(channel()) cv::Ma…

搭建基于VsCode的ESP32的開發環境教程

一、VsCode搜索ESP-IDF插件 根據插件處搜索找到ESP-IDF并安裝 安裝完成 二、配置安裝ESP-IDF 配置IDF 按照如下配置&#xff0c;點擊安裝 安裝完成 三、使用案例程序 創建一個閃光燈的例子程序&#xff0c;演示程序編譯下載。 選擇blink例子&#xff0c;閃爍LED的程序 選…

企業培訓學習考試系統源碼 ThinkPHP框架+Uniapp支持多終端適配部署

在數字化轉型浪潮下&#xff0c;企業對高效培訓與精準考核的需求日益迫切。一套功能完備、多終端適配且易于定制的培訓學習考試系統&#xff0c;成為企業提升員工能力、檢驗培訓成果的關鍵工具。本文給大家分享一款基于 ThinkPHP 框架與 Uniapp 開發的企業培訓學習考試系統&…

【PmHub面試篇】PmHub集成Redission分布式鎖保障流程狀態更新面試專題解析

你好&#xff0c;歡迎來到本次關于PmHub整合TransmittableThreadLocal (TTL)緩存用戶數據的面試系列分享。在這篇文章中&#xff0c;我們將深入探討這一技術領域的相關面試題預測。若想對相關內容有更透徹的理解&#xff0c;強烈推薦參考之前發布的博文&#xff1a;【PmHub后端…

mac 設置cursor (像PyCharm一樣展示效果)

一、注冊 Cursor - The AI Code Editor 二、配置Python環境 我之前使用pycharm創建的python項目&#xff0c;以及創建了虛擬環境&#xff0c;現在要使用cursor繼續開發。 2.1 選擇Python 虛擬環境 PyCharm 通常將虛擬環境存儲在項目目錄下的 venv 或 .venv 文件夾中&#xf…

Spring事務失效-----十大常見場景及解決方案全解析

Spring事務失效的常見場景及原因分析 Spring事務管理是開發中的核心功能,但在實際應用中可能因各種原因導致事務失效。以下是常見的事務失效場景及詳細解析: 1. 方法未被Spring管理 場景:使用new關鍵字直接創建對象,而非通過Spring容器注入原因:Spring事務基于AOP代理,…

剛出爐熱乎的。UniApp X 封裝 uni.request

HBuilder X v4.66 當前最新版本 由于 uniapp x 使用的是自己包裝的 ts 語言 uts。目前語言還沒有穩定下來&#xff0c;各種不支持 ts 各種報錯各種不兼容問題。我一個個問題調通的&#xff0c;代碼如下&#xff1a; 封裝方法 // my-app/utils/request.uts const UNI_APP_BASE…

【ArcGIS微課1000例】0148:Geographic Imager6.2使用教程

文章目錄 一、Geographic Imager6.2下載安裝二、Geographic Imager6.2使用方法1. 打開Geographic Imager2. 導入地理影像3. 導入DEM地形渲染4. 設置地理坐標系統5. 進行地理影像的處理6. 導出地理影像一、Geographic Imager6.2下載安裝 在專欄上一篇文章中已經詳細講述了Geogr…

零基礎安裝 Python 教程:從下載到環境配置一步到位(支持 VSCode 和 PyCharm)與常用操作系統操作指南

零基礎安裝 Python 教程&#xff1a;從下載到環境配置一步到位&#xff08;支持 VSCode 和 PyCharm&#xff09;與常用操作系統操作指南 本文是一篇超詳細“Python安裝教程”&#xff0c;覆蓋Windows、macOS、Linux三大操作系統的Python安裝方法與環境配置&#xff0c;包括Pyt…

定時任務的 cron 表達式

定時任務的 cron 表達式 一、什么時 cron 表達式 Cron表達式是一種廣泛應用于Linux系統的時間表示格式&#xff0c;常用于定時任務的調度。Cron表達式可以通過指定不同的時間參數&#xff0c;描述一個在 未來某個時間點執行的任務。 二、Cron表達式語法 秒 分 時 日 月 周幾…

PHP+mysql 美容美發預約小程序源碼 支持DIY裝修+完整圖文搭建教程

在數字化浪潮席卷的當下&#xff0c;美容美發行業也急需線上轉型&#xff0c;以提升客戶預約效率與服務體驗。開發一款美容美發預約小程序成為眾多商家的迫切需求。本文將為大家分享一套基于 PHPMySQL 的美容美發預約小程序源碼&#xff0c;功能完備、支持 DIY 裝修&#xff0c…

十八、【用戶認證篇】安全第一步:基于 JWT 的前后端分離認證方案

【用戶認證篇】安全第一步:基于 JWT 的前后端分離認證方案 前言什么是 JWT (JSON Web Token)?準備工作第一部分:后端 Django 配置 JWT 認證1. 安裝 `djangorestframework-simplejwt`2. 在 `settings.py` 中配置 `djangorestframework-simplejwt`3. 在項目的 `urls.py` 中添加…

03 Deep learning神經網絡的編程基礎 代價函數(Cost function)--吳恩達

深度學習中的損失函數(Cost Function)用于量化模型預測與真實數據的差距,是優化神經網絡的核心指標。以下是常見類型及數學表達: 核心原理 邏輯回歸通過sigmoid函數將線性預測結果轉換為概率: y ^ ( i ) \hat{y}^{(i)}

Linux信號捕捉技術深度解析

根據您的需求&#xff0c;文章可以聚焦技術實現與實踐的結合&#xff0c;以下提供幾個標題方案供選擇&#xff1a; 方案一&#xff08;學術向標題&#xff09; 《Linux信號捕捉機制全解析&#xff1a;內核態捕獲原理、可重入函數實踐與SIGCHLD異步處理中的volatile陷阱》 方案…

【大模型部署】mac m1本地部署 ChatGLM3-6B 超詳細教程

本人環境&#xff1a;macOS 15.5 (Sonoma) - Apple M1 / 16 G 目標&#xff1a;在 mac m1 16G 上 完全離線 的本地模型目錄上&#xff0c;跑通官方 ChatGLM3-6B 目錄 背景 & 踩坑記錄 準備工作 新建 Conda 環境并安裝依賴 關鍵環境變量 運行 composite_demo 常見報錯與…