mardi 28 juin 2016

Accessing a url in a Flask view

I am trying to access an external url https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=184&format=json in a Flask view

I get the error,

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

Is that my local server that flask is looking for this url on. And if so why? I am running flask locally.

The view,

from flask import Flask, Response
import json
import urllib2

app = Flask(__name__)

@app.route('/')
def test():
    return 'Everything is running!'

@app.route('/stopid')
def stopid():
    dublin_bus_url = "https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=184&format=json"
    response = urllib2.urlopen(dublin_bus_url)
    json_response = json.load(response)
    routes = set()
    for result in json_response["results"]:
        routes.add(result["route"])

    return json.dumps(list(routes))

if __name__ == '__main__':
    app.run()

The index.html and script is,

<!DOCTYPE html>
<html>
<head>
  <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
  <script>
    d3.json("/stopid", function(error, routes) {
      routes.forEach(function(route) {
        console.log(route)
      });
    });
  </script>
</body>
</html>

I am new to Flask but this must not be the way to deal with an external link in a view.

The code above is adopted from this excellent tutorial for the Donorschoose api. https://youtu.be/bzl4hCH2CdY

Thanks,

Aucun commentaire:

Enregistrer un commentaire