Start the application:<\/li><\/ol>uvicorn app:app --reload<\/pre>You can view the application by accessing http:\/\/localhost:8000. The default language is English and you can pass the URL parameters language<\/code> to switch languages, such as http:\/\/localhost:8000\/?language=zh. <\/p>\nIn the above example, we use the internationalization middleware provided by FastAPI to specify the user's language preference by adding Accept-Language in the HTTP request header to achieve multi-language support. In the application, we use the Jinja2 template engine to render the page, and introduce translation by using {{ _('xxx') }}<\/code> in the template. <\/p>\nThrough the above examples, we can easily build a web application that supports internationalization under the FastAPI framework to provide a better user experience and global services. <\/p>"}
Home
Backend Development
Python Tutorial
Build international web applications using the FastAPI framework
Build international web applications using the FastAPI framework
Sep 29, 2023 pm 03:53 PM
fastapi
web application
globalization

Use the FastAPI framework to build international Web applications
FastAPI is a high-performance Python Web framework that combines Python type annotations and high-performance asynchronous support , making developing web applications easier, faster and more reliable. When building an international Web application, FastAPI provides convenient tools and concepts that can make the application easily support multiple languages.
Below I will give a specific code example to introduce how to use the FastAPI framework to build a web application that supports internationalization:
- First, we need to install FastAPI and the corresponding dependencies Library. You can use pip to install:
pip install fastapi[all]
- Create an app.py file to define the web application:
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()
# 加載靜態(tài)文件
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方法獲取表單提交的數(shù)據(jù)并返回
@app.post("/form")
async def form_post(request: Request):
form_data = await request.form()
return {"data": form_data}
- In the project root directory Create a translations folder and create an en folder in it to store English translation files. Create a messages.po file in the en folder to define English translation:
msgid "Hello"
msgstr "Hello"
msgid "Submit"
msgstr "Submit"
- Create an index.html file in the templates folder to define page templates:
<!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>
- Start the application:
uvicorn app:app --reload
You can view the application by accessing http://localhost:8000. The default language is English and you can pass the URL parameters language
to switch languages, such as http://localhost:8000/?language=zh.
In the above example, we use the internationalization middleware provided by FastAPI to specify the user's language preference by adding Accept-Language in the HTTP request header to achieve multi-language support. In the application, we use the Jinja2 template engine to render the page, and introduce translation by using {{ _('xxx') }}
in the template.
Through the above examples, we can easily build a web application that supports internationalization under the FastAPI framework to provide a better user experience and global services.
The above is the detailed content of Build international web applications using the FastAPI framework. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Build international web applications using the FastAPI framework
Sep 29, 2023 pm 03:53 PM
Use the FastAPI framework to build international Web applications. FastAPI is a high-performance Python Web framework that combines Python type annotations and high-performance asynchronous support to make developing Web applications simpler, faster, and more reliable. When building an international Web application, FastAPI provides convenient tools and concepts that can make the application easily support multiple languages. Below I will give a specific code example to introduce how to use the FastAPI framework to build
Django, Flask, and FastAPI: Choose the one that best suits your development needs
Sep 29, 2023 am 10:49 AM
Django, Flask, and FastAPI: Choose the one that best suits your development needs, specific code examples required Introduction: In modern web development, choosing the right framework is crucial. As Python continues to develop in the field of web development, frameworks such as Django, Flask and FastAPI are becoming more and more popular among developers. This article will introduce the characteristics and applicable scenarios of these three frameworks, combined with specific code examples, to help you choose the framework that best suits your development needs. 1. D
How does PHP8 improve the performance of web applications through JIT compilation?
Oct 18, 2023 am 08:04 AM
How does PHP8 improve the performance of web applications through JIT compilation? With the continuous development of Web applications and the increase in demand, improving the performance of Web applications has become one of the focuses of developers. As a commonly used server-side scripting language, PHP has always been loved by developers. The JIT (just-in-time compilation) compiler was introduced in PHP8, providing developers with a new performance optimization solution. This article will discuss in detail how PHP8 can improve the performance of web applications through JIT compilation, and provide specific code examples.
Building Multilingual Websites with PHP: Eliminating Language Barriers
Feb 19, 2024 pm 07:10 PM
1. Prepare the database to create a new table for multilingual data, including the following fields: CREATETABLEtranslations(idINTNOTNULLAUTO_INCREMENT,localeVARCHAR(255)NOTNULL,keyVARCHAR(255)NOTNULL,valueTEXTNOTNULL,PRIMARYKEY(id)); 2. Set the language switching mechanism on the website Add a language switcher to the top or sidebar to allow users to select their preferred language. //Get the current language $current_locale=isset($_GET["locale"])?$_
How to deal with multi-language and internationalization issues in PHP development
Oct 09, 2023 pm 04:24 PM
How to deal with multi-language and internationalization issues in PHP development requires specific code examples. With the development of the Internet, people's demand for multi-language and internationalization is getting higher and higher. In PHP development, how to effectively handle multi-language and internationalization issues has become an important task that developers need to solve. Handling of character encoding In PHP development, we must first ensure that character encoding is handled correctly. In multi-language environments, using UTF-8 encoding is the most common choice. You can add the following code to the head of the PHP file: header('C
MySQL's Role: Databases in Web Applications
Apr 17, 2025 am 12:23 AM
The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.
How to use the Hyperf framework for internationalization support
Oct 22, 2023 am 08:14 AM
How to use the Hyperf framework for international support With the rapid development of globalization, many applications need to have multi-language support functions to meet the needs of users in different countries and regions. As a lightweight, high-performance framework, the Hyperf framework provides international support functions and can help developers quickly develop multi-language applications. This article will introduce how to use internationalization functions in the Hyperf framework and provide corresponding code examples. 1. Configure multi-language support. First, you need to configure the Hyperf configuration file.
Flask vs FastAPI: The best choice for building efficient APIs
Sep 29, 2023 am 09:29 AM
FlaskvsFastAPI: The best choice for building efficient APIs, specific code examples are required Introduction: With the development of the Internet, APIs have become one of the core components of modern applications. Building APIs that are efficient, reliable, and easy to develop is one of the top priorities for developers. In the Python field, the two most popular web frameworks, Flask and FastAPI, are widely used to build APIs. This article will compare the two frameworks and give code examples to illustrate their differences,
See all articles