外部 API 在 Django 中使用代理请求
External API Request with Proxy within Django
我在 127.0.0.1:8080
有一个本地代理服务
我可以用它进行 api 调用,但不能在 django 中调用,出于某种原因,它可以在常规 python 代码(即 python test.py
)中使用,但不能在 django 中使用。
import requests
proxies = {
'http': 'http://127.0.0.1:8080',
'https': 'https://127.0.0.1:8080',
}
response = requests.get('https://api.ipify.org?format=json', proxies=proxies)
django v3.0.8
并请求 v2.24.0
我假设 WSGI 以某种方式覆盖了我的代理设置
错误
HTTPSConnectionPool(host='api.ipify.org', port=443): Max retries exceeded with url: /?format=json (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fa922093340>: Failed to establish a new connection: [Errno 111] Connection refused')))
对于遇到此问题的任何人,这是一个 docker 网络问题。 docker 容器中的 127.0.0.1
引用内部 docker 网络,而不是您本地环境的网络。使用 172.17.0.1
指定您的本地环境。
我在 127.0.0.1:8080
我可以用它进行 api 调用,但不能在 django 中调用,出于某种原因,它可以在常规 python 代码(即 python test.py
)中使用,但不能在 django 中使用。
import requests
proxies = {
'http': 'http://127.0.0.1:8080',
'https': 'https://127.0.0.1:8080',
}
response = requests.get('https://api.ipify.org?format=json', proxies=proxies)
django v3.0.8
并请求 v2.24.0
我假设 WSGI 以某种方式覆盖了我的代理设置
错误
HTTPSConnectionPool(host='api.ipify.org', port=443): Max retries exceeded with url: /?format=json (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fa922093340>: Failed to establish a new connection: [Errno 111] Connection refused')))
对于遇到此问题的任何人,这是一个 docker 网络问题。 docker 容器中的 127.0.0.1
引用内部 docker 网络,而不是您本地环境的网络。使用 172.17.0.1
指定您的本地环境。