如何从flask中调用另一个webservice api [英] how to call another webservice api from flask

查看:91
本文介绍了如何从flask中调用另一个webservice api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

该网址从逻辑上更改为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.

推荐答案

您需要向服务器请求"数据,然后将其发送.

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

您可以使用python stdlib函数(urllib等),但这很尴尬,因此很多人都在使用"requests"库.( pip安装请求)

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 )

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


如果由于任何原因而无法安装 requests ,请按照以下方法使用


If you cannot install requests, for whatever reason, here's how to do it with the standard library (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)安全证书,这在某些情况下可能是一个问题(例如

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)

我真的建议使用 requests 模块.

这篇关于如何从flask中调用另一个webservice api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆