
客户端
使用 FastAPI(starlette)框架开发 Web 应用程序时,有时需要获取客户端的真实 IP 地址。本文将介绍如何在 FastAPI 中获取客户端真实 IP 的方法,并提供一个案例代码进行演示。
在 Web 开发中,获取客户端真实 IP 地址对于一些场景是非常重要的,比如限制特定 IP 地址的访问权限、统计用户地理位置信息等。然而,由于代理服务器的存在,直接通过获取请求的request.client.host 属性无法获取到真实的客户端 IP 地址。为了解决这个问题,我们可以通过访问请求头中的特定字段来获取客户端的真实 IP 地址。在 FastAPI(基于 starlette 框架)中,可以通过访问 request.headers 来获取请求头信息。为了方便获取客户端真实 IP 地址,我们可以使用 starlette 框架提供的 ClientDisconnect 类。这个类提供了一个 get_peername 方法,可以获取到客户端的 IP 地址和端口号。下面是一个示例代码,演示如何在 FastAPI 中获取客户端真实 IP 地址:Pythonfrom fastapi import FastAPIfrom starlette.middleware.base import BaseHTTPMiddlewarefrom starlette.types import ASGIApp, Scope, Receive, Sendfrom starlette.requests import Requestfrom socket import socketapp = FastAPI()class ClientIPMiddleware(BaseHTTPMiddleware): async def dispatch( self, request: Request, call_next: ASGIApp ) -> Response: async def receive() -> Receive: return awAIt request._receive() async def send(message: Message) -> None: if message["type"] == "http.response.start": # 获取客户端 IP 地址和端口号 ip, port = request.scope.get("client") request.client_host = ip awAIt request._send(message) scope = request.scope connection = scope.get("connection") if connection is not None and isinstance(connection, socket): # 获取客户端 IP 地址和端口号 ip, port = connection.getpeername() request.client_host = ip response = awAIt call_next(request) return responseapp.add_middleware(ClientIPMiddleware)@app.get("/ip")def get_client_ip(request: Request): client_ip = request.client_host return {"client_ip": client_ip}在上述代码中,我们定义了一个名为 ClientIPMiddleware 的中间件类,继承自 BaseHTTPMiddleware。在 dispatch 方法中,我们通过访问 request.scope 和 request._receive() 获取到客户端 IP 地址,并将其赋值给 request.client_host 属性。接着,我们使用 app.add_middleware(ClientIPMiddleware) 将这个中间件添加到 FastAPI 应用程序中,以便在每个请求中都能获取到客户端真实 IP 地址。最后,我们定义一个路由函数 get_client_ip,通过访问 request.client_host 属性获取到客户端 IP 地址,并返回给客户端。示例代码解析:在示例代码中,我们首先导入了所需的模块和类,包括 FastAPI、BaseHTTPMiddleware、ASGIApp、Scope、Receive、Send、Request 和 socket。然后,我们初始化了一个 FastAPI 应用程序,命名为 app。接下来,我们定义了一个名为 ClientIPMiddleware 的中间件类,继承自 BaseHTTPMiddleware。在这个类中,我们重写了 dispatch 方法,并通过访问 request.scope 和 request._receive() 获取到客户端 IP 地址。我们将获取到的 IP 地址赋值给 request.client_host 属性。在 dispatch 方法中,我们还通过访问 request.scope 和 request._send() 获取到客户端的 IP 地址和端口号,并将其赋值给 request.client_host 属性。接着,我们使用 app.add_middleware(ClientIPMiddleware) 将中间件添加到 FastAPI 应用程序中。最后,我们定义了一个路由函数 get_client_ip,使用 @app.get 装饰器将其绑定到 /ip 路径上。在这个函数中,我们通过访问 request.client_host 属性获取到客户端 IP 地址,并将其返回给客户端。:在本文中,我们介绍了如何在 FastAPI(基于 starlette 框架)中获取客户端真实 IP 地址。通过访问请求头中的特定字段,我们可以获取到客户端的 IP 地址。我们还提供了一个案例代码进行演示,通过添加中间件和访问请求对象的属性,我们可以轻松地获取到客户端的真实 IP 地址。通过获取客户端真实 IP 地址,我们可以实现一些功能,比如限制特定 IP 地址的访问权限、统计用户地理位置信息等。这对于一些特定的业务场景非常有用。希望本文对你理解如何在 FastAPI 中获取客户端真实 IP 地址有所帮助!Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号