Skip to content

Commit

Permalink
Updated app to Python3.4
Browse files Browse the repository at this point in the history
  • Loading branch information
joengelm committed Oct 2, 2015
1 parent 519ba12 commit 0c4f971
Show file tree
Hide file tree
Showing 13 changed files with 81 additions and 101 deletions.
19 changes: 7 additions & 12 deletions api/__init__.py
@@ -1,5 +1,4 @@
from flask import Flask, jsonify, request, current_app, url_for
from flask_limiter import Limiter
from werkzeug.exceptions import default_exceptions
from werkzeug.exceptions import HTTPException
from functools import wraps
Expand Down Expand Up @@ -38,28 +37,24 @@ def decorated_function(*args, **kwargs):
try:
app.config.from_object('config') # load default config file
except IOError:
print "Could not load default config file!"
print("Could not load default config file!")

try:
app.config.from_pyfile('config.py') # load instance config file
except IOError:
print "Could not load instance config file!"
print("Could not load instance config file!")

# override all error handlers to be 'make_json_error'
for code in default_exceptions.iterkeys():
for code in default_exceptions:
app.error_handler_spec[None][code] = make_json_error

if 'MONGO_URI' in app.config:
db = pymongo.MongoClient(app.config['MONGO_URI']).brown
elif 'MONGO_URI' in os.environ:
db = pymongo.MongoClient(os.environ['MONGO_URI']).brown
else:
print "The database URI's environment variable was not found."
print("The database URI's environment variable was not found.")

# setup rate limiting
RATE_LIMIT = "10/second;100/minute"
limiter = Limiter(app, global_limits=["10/second", "100/minute"], key_func=lambda : request.args.get('client_id', 'missing_client'))

import meta
import dining
import wifi
import api.meta
import api.dining
import api.wifi
11 changes: 2 additions & 9 deletions api/dining.py
@@ -1,6 +1,6 @@
from flask import request, jsonify
from api import app, db, make_json_error, limiter, RATE_LIMIT, support_jsonp
from meta import is_valid_client, log_client, INVALID_CLIENT_MSG
from api import app, db, make_json_error, support_jsonp
from api.meta import is_valid_client, log_client, INVALID_CLIENT_MSG

from datetime import datetime, date, timedelta
from difflib import get_close_matches
Expand All @@ -23,7 +23,6 @@


@app.route('/dining')
@limiter.shared_limit(RATE_LIMIT, 'dining')
@support_jsonp
def dining_index():
client_id = request.args.get('client_id', 'missing_client')
Expand All @@ -35,7 +34,6 @@ def dining_index():


@app.route('/dining/menu')
@limiter.shared_limit(RATE_LIMIT, 'dining')
@support_jsonp
def req_dining_menu():
''' Endpoint for all menu requests (see README for documentation) '''
Expand Down Expand Up @@ -93,7 +91,6 @@ def req_dining_menu():


@app.route('/dining/hours')
@limiter.shared_limit(RATE_LIMIT, 'dining')
@support_jsonp
def req_dining_hours():
''' Endpoint for all hours requests (see README for documentation) '''
Expand Down Expand Up @@ -131,7 +128,6 @@ def req_dining_hours():


@app.route('/dining/find')
@limiter.shared_limit(RATE_LIMIT, 'dining')
@support_jsonp
def req_dining_find():
''' Endpoint for requests to find food (see README for documentation) '''
Expand All @@ -155,7 +151,6 @@ def req_dining_find():


@app.route('/dining/nutrition')
@limiter.shared_limit(RATE_LIMIT, 'dining')
@support_jsonp
def req_dining_nutrition():
''' Endpoint for nutrtitional requests (see README for documentation) '''
Expand All @@ -176,7 +171,6 @@ def req_dining_nutrition():


@app.route('/dining/open')
@limiter.shared_limit(RATE_LIMIT, 'dining')
@support_jsonp
def req_dining_open():
''' Endpoint for open eatery requests (see README for documentation) '''
Expand Down Expand Up @@ -232,7 +226,6 @@ def req_dining_open():
return jsonify(open_eateries=open_eateries)

@app.route('/dining/all_food')
@limiter.shared_limit(RATE_LIMIT, 'dining')
@support_jsonp
def req_dining_all_food():
''' Endpoint for all food requests (see README for documentation) '''
Expand Down
14 changes: 6 additions & 8 deletions api/meta.py
@@ -1,8 +1,8 @@
from flask import jsonify, render_template, url_for, request, redirect
from api import app, db, limiter, RATE_LIMIT
from scripts.add_client import add_client_id
from scripts.email_handler import send_id_email
from scripts.stats import get_total_requests
from api import app, db
from api.scripts.add_client import add_client_id
from api.scripts.email_handler import send_id_email
from api.scripts.stats import get_total_requests

'''
DATABASE OBJECTS: View templates on the private, repository README.
Expand All @@ -17,7 +17,6 @@


@app.route('/')
@limiter.limit(RATE_LIMIT)
def root():
signed_up = request.args.get('signedup', '')
num_requests = get_total_requests()
Expand All @@ -31,7 +30,6 @@ def root():


@app.route('/signup', methods=['GET', 'POST'])
@limiter.limit(RATE_LIMIT)
def signup():
if request.method == 'GET':
return render_template('signup.html')
Expand Down Expand Up @@ -64,7 +62,7 @@ def is_valid_client(client_id):
if client and 'valid' in client and client['valid']:
# client exists in database and is marked as valid
return True
print "Client ID", client_id, "not found in client collection"
print("Client ID", client_id, "not found in client collection")
return False

def log_client(client_id, endpoint, timestamp):
Expand All @@ -74,7 +72,7 @@ def log_client(client_id, endpoint, timestamp):
result = clients.update({'client_id': client_id}, {'$inc': {'requests': 1}, '$push': {'activity': {'endpoint': endpoint, 'timestamp': timestamp}}})
if u'nModified' in result and result[u'nModified'] == 1:
return True
print "Bad result from log_client: ", result
print("Bad result from log_client: ", result)
return False

def invalidate_client(client_id):
Expand Down
16 changes: 8 additions & 8 deletions api/scripts/add_client.py
Expand Up @@ -12,10 +12,10 @@

def add_client_id(email, username, client_id=None):
if email[-10:] != '@brown.edu':
print "Invalid student email"
print("Invalid student email")
return None
if clients.find({'client_email': email}).count() >= MAX_IDS_PER_STUDENT:
print "Student email is already associated with 1 or more IDs"
print("Student email is already associated with 1 or more IDs")
return None
if not client_id:
client_id = str(uuid4())
Expand All @@ -33,10 +33,10 @@ def add_client_id(email, username, client_id=None):

if __name__ == '__main__':
if len(argv) < 2 or len(argv) > 3:
print "Usage: python -m api.scripts.add_client <client_name> <client_email> <username> [client_id]"
print "\tclient_email - Required. An @brown.edu email address."
print "\tusername - Required. A user who owns this client (typically a first and last name, like 'Josiah Carberry')."
print "\tclient_id - Optional. Provide a string representation of a UUID4 client ID."
print("Usage: python -m api.scripts.add_client <client_name> <client_email> <username> [client_id]")
print("\tclient_email - Required. An @brown.edu email address.")
print("\tusername - Required. A user who owns this client (typically a first and last name, like 'Josiah Carberry').")
print("\tclient_id - Optional. Provide a string representation of a UUID4 client ID.")
exit()

if len(argv) == 3:
Expand All @@ -45,6 +45,6 @@ def add_client_id(email, username, client_id=None):
client_id = add_client_id(argv[1], argv[2], client_id=argv[3])

if not client_id:
print "Email is not a Brown address. Unable to add client to database."
print("Email is not a Brown address. Unable to add client to database.")
else:
print "Client ID: ", client_id
print("Client ID: ", client_id)
4 changes: 2 additions & 2 deletions api/scripts/disable_client.py
Expand Up @@ -4,6 +4,6 @@

if __name__ == '__main__':
if len(argv) != 2:
print "Usage: python -m api.scripts.disable_client <client_id>"
print("Usage: python -m api.scripts.disable_client <client_id>")
else:
print meta.invalidate_client(argv[1])
print(meta.invalidate_client(argv[1]))
39 changes: 20 additions & 19 deletions api/scripts/eateries.py
@@ -1,4 +1,5 @@
from urllib2 import Request, unquote, urlopen
import requests
from urllib.parse import unquote
from bs4 import BeautifulSoup as soup
from datetime import date, timedelta
import time
Expand Down Expand Up @@ -171,14 +172,14 @@ def scrape_menus(self):
import time
time.sleep(1) # delays for 1 second (BDS rate limits their site)
try:
print meal, "for", day, menu_date, "->", self.scrape_menu(menu_date, day, meal)
print(meal, "for", day, menu_date, "->", self.scrape_menu(menu_date, day, meal))
num_menus += 1
except:
error_did_occur = True
import traceback
traceback.print_exc()
print "Could not scrape data for", meal, "on", day, menu_date
print "Attempting to continue..."
print("Could not scrape data for", meal, "on", day, menu_date)
print("Attempting to continue...")
menu_date += timedelta(1)
if error_did_occur:
raise RuntimeError("Could not scrape data for at least one VDub meal.")
Expand Down Expand Up @@ -230,29 +231,29 @@ def scrape_hours(self):

today = date.today()
if today > date(2015, 12, 22):
print "ERROR: hours scraper is out of date"
print("ERROR: hours scraper is out of date")
return num_hours
while today < date(2015, 12, 22):
if today.month == 11 and today.day == 6:
# Thanksgiving (open 11:30AM-7:30PM)
num_hours += 1
print "hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (11, 30), (19, 30))
print("hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (11, 30), (19, 30)))
elif today.month == 11 and today.day >= 27 and today.day <= 29:
# Thanksgiving weekend (10:30AM-7:30AM)
num_hours += 1
print "hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (10, 30), (19, 30))
print("hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (10, 30), (19, 30)))
elif today.month == 12 and today.day == 20:
# Finals period Sunday schedule (Weekday hours)
num_hours += 1
print "hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (19, 30))
print("hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (19, 30)))
elif today.weekday() == 6:
# Sunday brunch schedule
num_hours += 1
print "hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (10, 30), (19, 30))
print("hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (10, 30), (19, 30)))
elif today.weekday() != 6:
# weekday and Saturday schedule
num_hours += 1
print "hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (19, 30))
print("hours for {0}/{1}/{2} ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (19, 30)))
today = today + timedelta(1)
return num_hours

Expand Down Expand Up @@ -307,15 +308,15 @@ def scrape_menus(self):
try:
menu_ids = self.scrape_menu(menu_date, day, days_meals[day], n)
for menu_id in menu_ids:
print menu_id[0], "for", day, menu_date, "->", menu_id[1]
print(menu_id[0], "for", day, menu_date, "->", menu_id[1])
num_menus += 1
menu_date += timedelta(1)
except:
error_did_occur = True
import traceback
traceback.print_exc()
print "Could not scrape data for", menu_id[0], "on", day, menu_date
print "Attempting to continue..."
print("Could not scrape data for", menu_id[0], "on", day, menu_date)
print("Attempting to continue...")
if error_did_occur:
raise RuntimeError("Could not scrape data for at least one VDub meal.")
return num_menus
Expand Down Expand Up @@ -375,7 +376,7 @@ def scrape_hours(self):

today = date.today()
if today > date(2015, 12, 22):
print "ERROR: hours scraper is out of date"
print("ERROR: hours scraper is out of date")
return num_hours
while today < date(2015, 12, 22):
if today.month == 10 and today.day >= 10 and today.day <= 11:
Expand All @@ -387,7 +388,7 @@ def scrape_hours(self):
elif today.month == 11 and today.day == 25:
# wednesday before thxgiving
num_hours += 1
print "hours for {0}/{1}/{2} (breakfast/lunch) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (14, 00))
print("hours for {0}/{1}/{2} (breakfast/lunch) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (14, 00)))
elif today.month == 11 and today.day >= 26 and today.day <= 29:
# thxgiving weekend
pass
Expand All @@ -397,15 +398,15 @@ def scrape_hours(self):
elif today.month == 12 and today.day == 21:
# last day of finals
num_hours += 1
print "hours for {0}/{1}/{2} (breakfast/lunch) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (14, 00))
print("hours for {0}/{1}/{2} (breakfast/lunch) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (14, 00)))
elif today.weekday() >= 5:
# weekend schedule
pass
elif today.weekday() <= 4:
# weekday schedule
num_hours += 2
print "hours for {0}/{1}/{2} (breakfast/lunch) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (14, 00))
print "hours for {0}/{1}/{2} (dinner) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (16, 30), (19, 30))
print("hours for {0}/{1}/{2} (breakfast/lunch) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (7, 30), (14, 00)))
print("hours for {0}/{1}/{2} (dinner) ->".format(today.month, today.day, today.year), self.add_hours_to_db(today.year, today.month, today.day, (16, 30), (19, 30)))
today = today + timedelta(1)

return num_hours
Expand Down Expand Up @@ -436,7 +437,7 @@ def scrape_hours(self):

def get_html(url):
''' The HTML data for a given URL '''
return urlopen(Request(url)).read()
return requests.get(url).text

def flatten(dct):
''' Flatten a dictionary's values into a list '''
Expand Down
4 changes: 2 additions & 2 deletions api/scripts/email_handler.py
Expand Up @@ -61,7 +61,7 @@ def send_id_email(address, firstname, client_id):

# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
print s.sendmail(me, address, msg.as_string())
print(s.sendmail(me, address, msg.as_string()))
s.quit()

# Example usage of the above method:
Expand Down Expand Up @@ -117,7 +117,7 @@ def send_alert_email(message, urgent=False):

# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
print s.sendmail(me, recepient, msg.as_string())
print(s.sendmail(me, recepient, msg.as_string()))
s.quit()

# Example usage of the above method:
Expand Down
4 changes: 2 additions & 2 deletions api/scripts/enable_client.py
Expand Up @@ -4,6 +4,6 @@

if __name__ == '__main__':
if len(argv) != 2:
print "Usage: python -m api.scripts.enable_client <client_id>"
print("Usage: python -m api.scripts.enable_client <client_id>")
else:
print meta.validate_client(argv[1])
print(meta.validate_client(argv[1]))

0 comments on commit 0c4f971

Please sign in to comment.