首頁  >  文章  >  後端開發  >  使用FastAPI框架建構國際化的Web應用

使用FastAPI框架建構國際化的Web應用

PHPz
PHPz原創
2023-09-29 15:53:081217瀏覽

使用FastAPI框架建構國際化的Web應用

使用FastAPI框架建立國際化的Web應用

FastAPI是一個高效能的Python Web框架,它結合了Python類型註解和效能較好的非同步支持,使得開發網頁應用程式變得更加簡單、快速、可靠。在建立一個國際化的網路應用程式時,FastAPI提供了方便的工具和理念,讓應用程式能夠輕鬆支援多種語言。

下面我將給出一個具體的程式碼範例,介紹如何使用FastAPI框架建立一個支援國際化的Web應用:

  1. 首先,我們需要安裝FastAPI和對應的依賴庫。可以使用pip進行安裝:
pip install fastapi[all]
  1. 建立一個app.py文件,用於定義Web應用:
from typing import Optional
from fastapi import FastAPI
from fastapi import Request, Depends
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from starlette.templating import Jinja2Templates
from starlette.requests import Request
from fastapi.i18n import (
    I18nMiddleware, 
    get_accept_languages
)

app = FastAPI()

# 加载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 初始化国际化中间件
app.add_middleware(I18nMiddleware, default_language="en", translation_directory="translations")

templates = Jinja2Templates(directory="templates")

# 通过GET方法获取主页面
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request, languages: str = Depends(get_accept_languages)):
    return templates.TemplateResponse("index.html", {"request": request, "languages": languages})

# 通过POST方法获取表单提交的数据并返回
@app.post("/form")
async def form_post(request: Request):
    form_data = await request.form()
    return {"data": form_data}
  1. 在專案根目錄下建立一個translations資料夾,並在其中建立一個en資料夾,用於存放英文翻譯檔案。在en資料夾中建立一個messages.po文件,用於定義英文翻譯:
msgid "Hello"
msgstr "Hello"

msgid "Submit"
msgstr "Submit"
  1. 在templates資料夾下建立一個index.html文件,用於定義頁面模板:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{ _('Welcome to my website') }}</title>
</head>
<body>
    <h1>{{ _('Hello') }}</h1>
    <p>{{ _('This is a sample web application') }}</p>
    
    <form action="/form" method="post">
        <input type="text" name="name" placeholder="{{ _('Enter your name') }}">
        <button type="submit">{{ _('Submit') }}</button>
    </form>
    
    <h2>{{ _('Supported Languages') }}</h2>
    <ul>
    {% for language in languages %}
        <li><a href="/?language={{ language }}">{{ language }}</a></li>
    {% endfor %}
    </ul>
</body>
</html>
  1. 啟動應用程式:
uvicorn app:app --reload

透過造訪http://localhost:8000可以查看應用,預設語言為英語,可以透過URL參數 language來切換語言,例如http://localhost:8000/?language=zh。

以上範例中,我們使用了FastAPI提供的國際化中介軟體,透過在HTTP請求頭中加入Accept-Language來指定使用者的語言偏好,從而實現多語言支援。在應用程式中我們使用了Jinja2模板引擎來渲染頁面,透過在模板中使用{{ _('xxx') }}來引入翻譯。

透過上述範例,我們可以在FastAPI架構下輕鬆建立一個支援國際化的網路應用,提供更好的使用者體驗和全球化的服務。

以上是使用FastAPI框架建構國際化的Web應用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn