Skip to content

Instantly share code, notes, and snippets.

@nsmaciej
Last active August 29, 2015 14:04
Show Gist options
  • Save nsmaciej/0c748e79e7952057aca8 to your computer and use it in GitHub Desktop.
Save nsmaciej/0c748e79e7952057aca8 to your computer and use it in GitHub Desktop.
A simple python web server for returning live data from the London Underground. Example request: /B/BST/1
'''
The MIT License (MIT)
Copyright (c) 2014 Maciej Goszczycki
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''
import xml.dom.minidom as dom
import urllib2
import time
import flask
# Global cache
cache = {}
cacheDuration = 60 #sec
# Get URL Content
def getPlatform(line, station, platformno):
# Handle caching
global cache
cacheString = "{}/{}/{}".format(line, station, platformno)
cached = cache.get(cacheString, {})
if cached and cached['time'] + cacheDuration >= time.time():
print("'{}' cached at {}, returning".format(cacheString, cached['time']))
print("Current itme: {}".format(time.time()))
return cached['data']
# Make new request if caching failed
print("Missing or old cache making new request for {}".format(cacheString))
url = "http://cloud.tfl.gov.uk/TrackerNet/PredictionDetailed/{}/{}"
response = urllib2.urlopen(url.format(line, station))
xml = dom.parseString(response.read())
platformtrains = xml.getElementsByTagName('P')[platformno]
# Travserse the DOM
trains = map(lambda e: lambda v: e.attributes[v].value, platformtrains.getElementsByTagName('T'))
stname = xml.getElementsByTagName('S')[0].attributes['N'].value[:-1] #Remove the dot from the name
linename = xml.getElementsByTagName('LineName')[0].firstChild.nodeValue
platform = platformtrains.attributes['Num'].value
# Assign cache
data = (linename, stname, platform, trains)
cache[cacheString] = {'time': time.time(), 'data': data}
return data
# Create the Flask app
app = flask.Flask(__name__)
# Route for retriving platforms
@app.route('/<line>/<station>/<int:platform>')
def handlePlatform(line, station, platform):
# Train data
linename, stname, platform, trains = getPlatform(line, station, platform)
# Markup
header = "<h1>Trains on platfrom {}, on station {}, on line {}</h1>".format(platform, stname, linename)
tablepre = "<table><tr><th>Destination</th><th>Time to</th></tr>"
tablepost = "</table>"
# Produce the HTML
html = header + tablepre
for train in trains:
html += "<tr><td>{}</td><td>{}</td><tr>".format(train('Destination'), train('TimeTo').replace('-', '<i>Due</i>'))
html += tablepost
return html
# Start the server at :1024
if __name__ == "__main__":
app.run(port=1024, debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment