16

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.

Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39
user3089927
  • 3,575
  • 8
  • 25
  • 33

1 Answers1

29

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.

Daniel
  • 1,410
  • 12
  • 17
  • did the trick. Thanks. Also is there any other way too to do the stuff? – user3089927 Aug 06 '14 at 16:28
  • 3
    @user3089927: What do you mean by 'do the stuff'? – Daniel Aug 06 '14 at 16:50
  • sorry, just wanted to know if there are also other ways to solve this issue? – user3089927 Aug 06 '14 at 17:56
  • You could use `subprocess.check_output(['curl','http://www.google.com'])`, which would work on *NIX machines. You could put an iframe in your HTML `` type of thing (although that's cheating). You could use cross-domain XHR requests in javascript (https://developer.chrome.com/extensions/xhr), you could use any of the other cross-domain solutions in JS: http://jquery-howto.blogspot.co.uk/2013/09/jquery-cross-domain-ajax-request.html, ... – Daniel Aug 06 '14 at 18:07
  • one thing I noticed, you are returning r.text so its not rendering the complete page except just the text on it. Also, I see google.com page but it is just like a local copy of google.com so one can not function with that page. if you enter anything in the text box , it throws 404 error. – user3089927 Aug 06 '14 at 23:40
  • Sure. read the requests documentation to get the actual HTML. If you want to interact with the result that you're sending, then you'll need to edit the page. If the google page has an input box which tries to query `/search`, and your server doesn't have a `/search` route, then obviously it won't work. If you want to change the contents of the result your sending, then you need to parse the HTML, and change stuff. I recommend the bs4 (beautiful soup) library. – Daniel Aug 07 '14 at 09:39
  • The link is no longer available. – Catalina Chircu Jul 14 '20 at 08:11