from fastapi import Request def get_client_ip(request: Request) -> str: """ Using a testclient, the ip returned is 'testclient'. If so, instead, grab the ip from the headers """ ip = request.headers.get("X-Forwarded-For") if not ip: ip = request.client.host # type: ignore elif ip == "testclient" or ip.startswith("10."): forwarded = request.headers.get("X-Forwarded-For") ip = ( forwarded.split(",")[0].strip() if forwarded else request.client.host # type: ignore ) return ip