fastapi中文
Requests, Event Handlers, Environment Variables and WSGIMiddleware
请求,事件处理程序,环境变量和WSGIMiddleware
The topic for today is about four advanced features in FastAPI that might be useful in your web application. If you are new to FastAPI, it is highly recommended to follow the starter guide provided by the official documentation before you continue.
今天的主题是有关FastAPI中的四个高级功能的信息,这些功能可能在您的Web应用程序中很有用。 如果您不熟悉FastAPI,强烈建议您先阅读官方文档提供的入门指南,然后再继续。
Moreover, I have covered two FastAPI tutorials on How to Migrate From Flask to FastAPI and Smoothly and Metadata and Additional Responses in FastAPI. Feel free to check them out if you would like to learn more about the tips and tricks related to FastAPI. In this tutorial, I am going to explain the fundamental concepts behind:
此外,我还介绍了有关如何从Flask迁移到FastAPI以及平滑地迁移以及FastAPI中的元数据和其他响应的两个FastAPI教程。 如果您想了解更多有关FastAPI的提示和技巧,请随时查看它们。 在本教程中,我将解释背后的基本概念:
Request
— Using theRequest
object directly to get client address, request body, cookies, and etc.Request
-直接使用Request
对象获取客户地址,请求正文,Cookie等。Event handlers
— Register functions to be executed when the application starts or when the application shutdowns.Event handlers
-注册在应用程序启动或应用程序关闭时要执行的功能。Environment variables
— Handle configurations and settings related to your project.Environment variables
-处理与项目相关的配置和设置。WSGIMiddleware
— Include your Flask or Django server as sub application inside FastAPI.WSGIMiddleware
—将Flask或Django服务器作为子应用程序包含在FastAPI中。
1.要求 (1. Request)
The Request
object in FastAPI is based off Starlette’s Request
with additional tools on top of it. In fact, you can use it directly inside your path operation function to get details such as the client’s IP address. Have a look at the following code snippet. The API will return the client’s host and port when you call it.
FastAPI中的Request
对象基于Starlette的Request
并在其之上具有其他工具。 实际上,您可以在路径操作功能中直接使用它来获取详细信息,例如客户端的IP地址。 看一下下面的代码片段。 调用时,API将返回客户端的主机和端口。
- from fastapi import FastAPI, Request
-
-
- app = FastAPI()
-
-
- @app.get("/client-data")
- def client_data(request: Request):
- client_host = request.client.host
- client_port = request.client.port
-
- return {"client_host": client_host, "client_port": client_port}
Based on the official documentation, Request
object has the following commonly used fields:
根据官方文档&#x