我在 Flask 服务器中使用重定向来调用另一个 Web 服务 api.e.g
@app.route('/hello')
def hello():
return redirect("http://google.com")
网址逻辑上会更改为 google.com,但有什么方法可以保持相同的网址吗?
或任何其他方式来获得网络服务调用。
您需要向服务器“请求”数据,然后发送它。
你可以使用 python stdlib 函数(urllib 等),但它很尴尬,所以很多人使用“requests”库。 (pip install requests
)
http://docs.python-requests.org/en/latest/ http://docs.python-requests.org/en/latest/
所以你最终会得到类似的东西
@app.route('/hello')
def hello():
r = requests.get('http://www.google.com')
return r.text
如果无法安装requests
,无论出于何种原因,以下是如何使用标准库 https://docs.python.org/3.8/library/urllib.request.html(Python 3):
from urllib.request import urlopen
@app.route('/hello')
def hello():
with urlopen('http://www.google.com') as r:
text = r.read()
return text
使用 stdlib 版本意味着您最终将使用 stdlib SSL (https) 安全证书,这在某些情况下可能会出现问题(例如,有时在 macOS 上 https://stackoverflow.com/questions/50236117/scraping-ssl-certificate-verify-failed-error-for-http-en-wikipedia-org)
我真的推荐使用requests
module.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)