Skip to content

Instantly share code, notes, and snippets.

@pspeter3
Created September 9, 2013 23:04
Show Gist options
  • Save pspeter3/6502669 to your computer and use it in GitHub Desktop.
Save pspeter3/6502669 to your computer and use it in GitHub Desktop.
Status Board Foursquare Python Server
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from json import loads
from os import environ
from time import time
from urllib2 import urlopen
HEADER = environ.get('HEADER')
FOURSQUARE_URL = "https://api.foursquare.com/v2/checkins/recent?oauth_token=%s" % (environ.get('FOURSQUARE_TOKEN'))
FOURSQUARE_IDS = set(environ.get('FOURSQUARE_IDS').split(','))
def getDelta(timestamp):
"""Gets the detla of time in string"""
delta = int(time() - timestamp)
deltaString = ''
if delta > 31536000:
deltaString = str(delta/31536000) + 'y'
elif delta > 2592000:
deltaString = str(delta/2592000) + 'm'
elif delta > 86400:
deltaString = str(delta/86400) + 'd'
elif delta > 3600:
deltaString = str(delta/3600) + 'h'
elif delta > 60:
deltaString = str(delta/60) + 'm'
else:
deltaString = 'now'
return deltaString
def getInitial(name):
"""Gets the first letter as an initial and capitalizes it"""
return name[0].upper()
def getRow(checkin):
"""Convers a checkin into a row"""
user = checkin['user']
name = "%s%s" % (getInitial(user['firstName']), getInitial(user['lastName']))
venue = checkin['venue']['name']
time = getDelta(checkin['createdAt'])
display = "%s (%s)" %(venue, time)
return ",".join([name, display])
def getCheckins():
"""Gets the checkins from foursquare"""
data = loads(urlopen(FOURSQUARE_URL).read())
return [getRow(checkin) for checkin in data['response']['recent'] if checkin['user']['id'] in FOURSQUARE_IDS]
class StatusBoardHandler(BaseHTTPRequestHandler):
"""StatusBoardHandler handles requests from StatusBoard"""
def do_GET(self):
"""Handles all GET requests to the server"""
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
self.wfile.write("%s\n%s" % (HEADER, "\n".join(getCheckins())))
return
if __name__ == '__main__':
server = HTTPServer(('127.0.0.1', int(environ.get('PORT'))), StatusBoardHandler)
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment