-->

how to call another webservice api from flask

2020-07-05 11:07发布

问题:

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")

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.

回答1:

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 )

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):

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)

and I really recommend using the requests module.



标签: python flask