I take the IP address using client.host from the Request object and send this to another function, where I'm using Pydantic's IPvAnyAddress to validate the IP address.
Here is my code:
from fastapi import APIRouter, Request
from pydantic import IPvAnyAddress
route = APIRouter()
@route.get("/ip-address")
def request_ip_address_deblock_link(request: Request):
return example_function(request.client.host)
def example_function(ip_address: IPvAnyAddress):
print(ip_address)
But when I'm using FastAPI's TestClient to test my API routes, the IP-address check fails, as the hostname in the request is testclient.
ValueError: 'testclient' does not appear to be an IPv4 or IPv6 address
Is it possible to change the hostname in FastAPI/Starlette's TestClient?
testclientinstarlette.testclient.TestClient, but you might be able to go through having a customportal_factorythat changes the content ofscopebefore using the originalportal_factory? Also note that the TestClient changed from being based on requests to httpx in the last couple of days, so there might be a slight behavior change here (even if there shouldn't be one).portal_factoryis related toscope. Is it?scopeas one of its parameters. But it seems to only happen after the request has happened: github.com/encode/starlette/blob/… - I'm not familiar with the portal, but it's user configurable and has access toscopeat least somewhere in the request cycle, so that would be my best bet.