Skip to content

Commit

Permalink
FLAKE8 FIXES, hope I didn't break anything
Browse files Browse the repository at this point in the history
  • Loading branch information
hpincket committed Sep 1, 2016
1 parent cda071a commit c9fe6ed
Show file tree
Hide file tree
Showing 20 changed files with 362 additions and 345 deletions.
3 changes: 3 additions & 0 deletions .flake8
@@ -0,0 +1,3 @@
[flake8]
ignore=E501
exclude=venv,env
21 changes: 11 additions & 10 deletions api/__init__.py
Expand Up @@ -4,6 +4,11 @@
from functools import wraps
import pymongo
import os
import api.meta
import api.dining
import api.wifi
import api.laundry
import api.courses


def make_json_error(ex):
Expand All @@ -28,7 +33,6 @@ def support_jsonp(f):
def decorated_function(*args, **kwargs):
callback = request.args.get('callback', False)
if callback:
from json import dumps
content = callback.encode("utf-8") + b'(' + f(*args, **kwargs).data + b')'
return current_app.response_class(
content, mimetype='application/javascript')
Expand Down Expand Up @@ -79,6 +83,7 @@ def __init__(self, environ, populate_request=True, shallow=False):

# BASIC AUTH


def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
Expand All @@ -91,12 +96,14 @@ def check_auth(username, password):
print("The dashboard password's environment variable was not found.")
return username == 'admin' and password == correct_password


def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})


def requires_auth(f):
@wraps(f)
Expand All @@ -108,10 +115,4 @@ def decorated(*args, **kwargs):
return decorated


import api.meta
import api.dining
import api.wifi
import api.laundry
import api.courses

__all__ = ['api', ]
36 changes: 15 additions & 21 deletions api/courses.py
@@ -1,12 +1,10 @@
from flask import request, jsonify
from api import app, make_json_error, support_jsonp
from api.meta import is_valid_client, require_client_id, log_client, INVALID_CLIENT_MSG
from api.meta import require_client_id
from mongoengine import connect
import json
import urllib
from collections import defaultdict
import random
from api.scripts.coursemodels import *
from api.scripts.coursemodels import BannerCourse, NonconflictEntry
import bson
from datetime import date
import os
Expand All @@ -16,7 +14,7 @@
PAGINATION_LIMIT = 10
PAGINATION_MAX = 42

#TODO: Maybe there's some way to use the same connection as given by 'db'.
# TODO: Maybe there's some way to use the same connection as given by 'db'.

if 'MONGO_URI' in app.config:
connect('brown', host=app.config['MONGO_URI'])
Expand All @@ -35,7 +33,7 @@ def courses_index():
or
Returns the sections ids specified
'''
arg_numbers = request.args.get('numbers',None)
arg_numbers = request.args.get('numbers', None)
if arg_numbers is not None:
numbers = []
full_numbers = []
Expand Down Expand Up @@ -119,9 +117,9 @@ def schedule_time():
time = int(request.args.get('time', '-1'))
if time < 0:
return make_json_error("Invalid or Missing parameter: time")
query_args = {'meeting.day_of_week':day,
"meeting.start_time": {'$lte': time},
"meeting.end_time": {'$gte': time}}
query_args = {'meeting.day_of_week': day,
'meeting.start_time': {'$lte': time},
'meeting.end_time': {'$gte': time}}
return jsonify(paginate(filter_semester(query_args), params={'day': day, 'time': time}, raw=True))


Expand All @@ -136,21 +134,16 @@ def non_conflicting():
for course_number in courses:
res = BannerCourse.objects(full_number=course_number)
if len(res) <= 0:
return make_json_error(\
"Invalid course section/lab/conference:"\
+course_number)
return make_json_error("Invalid course section/lab/conference:" + course_number)
course = res.first().id
non_conflicting_list = NonconflictEntry.objects(course_id=course)
if len(non_conflicting_list) <= 0:
return make_json_error(\
"Error with course section/lab/conference:"\
+course_number)
return make_json_error("Error with course section/lab/conference:" + course_number)
non_conflicting_list = non_conflicting_list.first().non_conflicting
if available_set is None:
available_set = set(non_conflicting_list)
else:
available_set = set.intersection(available_set,
non_conflicting_list)
available_set = set.intersection(available_set, non_conflicting_list)
query_args = {"id__in": list(available_set)}
else:
# Slower method, a couple of seconds
Expand Down Expand Up @@ -192,19 +185,20 @@ def paginate(query, params=None, raw=False):
if '_id' not in query:
query['_id'] = {}
query['_id']['$gt'] = bson.objectid.ObjectId(offset)
res = list(BannerCourse.objects(__raw__=query).order_by('_id')[:limit+1])
res = list(BannerCourse.objects(__raw__=query).order_by('_id')[:limit + 1])
next_url = "null"
if len(res) == limit+1:
if len(res) == limit + 1:
next_url = request.base_url + "?" +\
urllib.parse.urlencode({"limit": limit,
"offset": res[limit - 1].id})
client_id = request.args.get('client_id')
next_url = next_url + "&" + urllib.parse.urlencode({"client_id": client_id})
if params is not None:
next_url = next_url+"&"+urllib.parse.urlencode(params)
next_url = next_url + "&" + urllib.parse.urlencode(params)
res.pop()

if offset is None: offset = "null"
if offset is None:
offset = "null"
ans = {"href": request.url,
"items": [json.loads(elm.to_json()) for elm in res],
"limit": limit,
Expand Down
15 changes: 9 additions & 6 deletions api/forms.py
Expand Up @@ -7,12 +7,13 @@
from api.scripts.add_documentation import add_documentation
from api.scripts.add_member import add_member


class SignupForm(Form):
name = StringField('Name', validators=[DataRequired()])
email = EmailField('Email', validators=[DataRequired(), Email()])

def validate(self):
if Form.validate(self):
if Form.validate(self):
client_id = add_client_id(self.email.data, self.name.data)
if client_id:
send_id_email(self.email.data, self.name.data, client_id)
Expand All @@ -23,16 +24,17 @@ def validate(self):
else:
return False


class DocumentationForm(Form):
name = StringField('Name', validators=[DataRequired()])
urlname = StringField('URL Name', validators=[DataRequired()])
imageurl = StringField('Image URL', validators=[DataRequired()])
contents = TextAreaField('Contents', validators=[DataRequired()])

def validate(self):
if Form.validate(self):
if Form.validate(self):
documentation = add_documentation(self.contents.data,
self.name.data, self.urlname.data, self.imageurl.data)
self.name.data, self.urlname.data, self.imageurl.data)
if documentation:
return True
else:
Expand All @@ -41,15 +43,16 @@ def validate(self):
else:
return False


class MemberForm(Form):
name = StringField('Name', validators=[DataRequired()])
imageurl = StringField('Image URL', validators=[DataRequired()])
about = TextAreaField('Contents', validators=[DataRequired()])

def validate(self):
if Form.validate(self):
if Form.validate(self):
member = add_member(self.about.data,
self.name.data, self.imageurl.data)
self.name.data, self.imageurl.data)
if member:
return True
else:
Expand Down
48 changes: 28 additions & 20 deletions api/meta.py

Large diffs are not rendered by default.

15 changes: 8 additions & 7 deletions api/scripts/add_client.py
Expand Up @@ -10,6 +10,7 @@
# simplify collection name
clients = db.clients


def add_client_id(email, username, client_id=None):
if email[-10:] != '@brown.edu':
print("Invalid student email")
Expand All @@ -22,12 +23,12 @@ def add_client_id(email, username, client_id=None):
while clients.find_one({'client_id': client_id}):
client_id = str(uuid4())
new_client = {
'client_id': client_id,
'username': username,
'client_email': email,
'joined': str(datetime.now()),
'valid': True
}
'client_id': client_id,
'username': username,
'client_email': email,
'joined': str(datetime.now()),
'valid': True
}
clients.insert(new_client)
return client_id

Expand All @@ -38,7 +39,7 @@ def add_client_id(email, username, client_id=None):
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:
client_id = add_client_id(argv[1], argv[2])
if len(argv) == 4:
Expand Down
11 changes: 6 additions & 5 deletions api/scripts/add_documentation.py
Expand Up @@ -2,12 +2,13 @@

api_documentations = db.api_documentations


def add_documentation(contents, name, urlname, imageurl):
new_documentation = {
'name': name,
'urlname': urlname,
'contents': contents,
'imageurl': imageurl
}
'name': name,
'urlname': urlname,
'contents': contents,
'imageurl': imageurl
}
api_documentations.insert(new_documentation)
return True
9 changes: 5 additions & 4 deletions api/scripts/add_member.py
Expand Up @@ -2,11 +2,12 @@

api_members = db.members


def add_member(about, name, imageurl):
new_member = {
'name': name,
'about': about,
'image_url': imageurl
}
'name': name,
'about': about,
'image_url': imageurl
}
api_members.insert(new_member)
return True
10 changes: 5 additions & 5 deletions api/scripts/disable_client.py
@@ -1,9 +1,9 @@
from sys import argv

from api import db, meta
from api import meta

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

0 comments on commit c9fe6ed

Please sign in to comment.