在尝试编写flask应用程序时,我在处理请求时使用requests对API进行出站HTTP调用时遇到了问题。如果我从python命令行运行相同的函数,它就可以工作。为什么?
我已经简化了我的flask应用程序,我得到了同样的错误。
import requests
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
try:
response = requests.get("https://httpbin.org/get")
data = response.json()
except Exception as e:
print(f"Caught exception {e}")
data = "no data: error"
return(f'<pre>{data}</pre>')
字符串
另存为sslerror.py
,需要安装flask
和requests
。
Web请求
我使用flask --app sslerror run
运行flask应用程序。Flask监听http://127.0.0.1:5000
。当我在浏览器中访问它时,我得到这个错误:
Caught exception HTTPSConnectionPool(host='httpbin.org', port=443): Max retries exceeded with url: /get (Caused by SSLError(SSLError(0, 'unknown error (_ssl.c:3098)')))`
型
Python REPL
另一方面,从命令行:
>>> from sslerror import hello_world
>>> hello_world()
"<pre>{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.31.0', 'X-Amzn-Trace-Id': 'Root=1-652f409a-abcdefabcdef'}, 'origin': '108.x.x.x', 'url': 'https://httpbin.org/get'}</pre>"
型
环境信息:苹果m2芯片上的MacOS 13.6(Ventura)。我使用pyenv的python 3.11.5。
我还尝试将verify=False
和allow_redirects=False
添加到get()
调用中,每次的结果都是一样的。
为什么出站HTTP请求在命令行中工作,但在flask请求的上下文中不工作?
- 更新:* 我也尝试了新的virtualenvs与python 3.8(从pyenv)和3.11从homebrew.相同的行为.
1条答案
按热度按时间eulz3vhy1#
我找到了一个解决方案,感谢this answer对一个不同的堆栈溢出问题:
字符串
(虽然我不明白为什么我在flask和REPL中得到了不同的行为)