Getting Python's requests library to use a local DNS (Core-DNS, Docker-compose, etc.) while behind a proxy

Getting Python's requests library to use a local DNS (Core-DNS, Docker-compose, etc.) while behind a proxy

When using Python's requests library, the requests are send through the proxy set as environment variables. Consequently, if the DNS to be used comes before said proxy, the host might not be resolved. This typically happens when resolving a host in Kubernetes using Core-DNS. If the request first leaves the Kubernetes cluster to reach the proxy, then the DNS server becomes unreachable, making the request fail.

To solve this problem, requests can be done using a session which ignores environment variables, so as to simulate a proxy-free setting:

session = requests.Session()
session.trust_env = False
response = session.post(api_url)