Within my code I take the IP-address from client.host
in the request
object and send this to another function. There I'm using the IPvAnyAddress
from Pydantic to validate if it is a valid 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 this hostname of FastAPI's TestClient
?
From Starlette's source code on testclient.py
here (that FastAPI actually uses under the hood, see here ), the testclient
hostname seems to be fixed/hardcoded.
Hence, you could simply check on server side if request.client.host == 'testclient'
inside a Dependency function (as @MatsLindh suggested in the comments section), and then, either ovveride testclient
with the local IP address (if you are testing this locally), or raise some exception .
Alternatively, you could use the HTTPX
library, also suggested in the FastAPI documentation . FastAPI/ Starlette 's TestClient
is now built on httpx
(see the relevant commit on github ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.