Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call another webservice api from flask

Tags:

python

flask

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.

like image 613
user3089927 Avatar asked Aug 05 '14 22:08

user3089927


People also ask

Can flask API handle multiple requests?

Improve performance in both Blocking and Non-Blocking web servers. Multitasking is the ability to execute multiple tasks or processes (almost) at the same time. Modern web servers like Flask, Django, and Tornado are all able to handle multiple requests simultaneously.


1 Answers

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.

like image 102
Daniel Avatar answered Sep 24 '22 16:09

Daniel