how to call another webservice api from flask

前端 未结 1 1507
梦毁少年i
梦毁少年i 2021-02-20 03:40

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


        
1条回答
  •  执念已碎
    2021-02-20 04:33

    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.

    0 讨论(0)
提交回复
热议问题