Python 如何从flask调用另一个webservice api

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25149493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:48:36  来源:igfitidea点击:

how to call another webservice api from flask

pythonflask

提问by user3089927

I am using redirect in my flask server to call another webservice api.e.g

我在我的烧瓶服务器中使用重定向来调用另一个 webservice api.eg

@app.route('/hello')
def hello():
    return redirect("http://google.com")

The url logically changes to google.com but is there any way that I keep the same url? or Anyother way to attain webservice calls.

url 在逻辑上更改为 google.com 但有什么办法可以保持相同的 url 吗?或任何其他方式获得网络服务调用。

采纳答案by Daniel

You need to 'request' the data to the server, and then send it.

您需要向服务器“请求”数据,然后将其发送。

You can use python stdlib functions (urllib, etc), but it's quite awkward, so a lot of people use the 'requests' library. ( pip install requests)

你可以使用 python stdlib 函数(urllib 等),但它很尴尬,所以很多人使用 'requests' 库。( pip install requests)

http://docs.python-requests.org/en/latest/

http://docs.python-requests.org/en/latest/

so you'd end up with something like

所以你最终会得到类似的东西

@app.route('/hello')
def hello():
    r = requests.get('http://www.google.com')
    return r.text


If you cannot install requests, for whatever reason, here's how to do it with the standard library(Python 3):

如果您无法安装requests,无论出于何种原因,以下是使用标准库(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

Using the stdlib version will mean you end up using the stdlib SSL (https) security certificates, which can be an issue in some circumstances (e.g. on macOS sometimes)

使用 stdlib 版本意味着您最终会使用 stdlib SSL (https) 安全证书,这在某些情况下可能是一个问题(例如有时在 macOS 上

and I really recommend using the requestsmodule.

我真的建议使用该requests模块。