Skip to content

Commit

Permalink
Move some views.py functions to here
Browse files Browse the repository at this point in the history
  • Loading branch information
EthanRosenthal committed Jan 8, 2017
1 parent ab2ba91 commit df21f91
Showing 1 changed file with 107 additions and 0 deletions.
107 changes: 107 additions & 0 deletions flask_app/app/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,113 @@
import yaml


def get_app_base_path():
return os.path.dirname(os.path.realpath(__file__))


def get_instance_folder_path():
return os.path.join(get_app_base_path(), 'instance')


def get_mid_data_from_db(mids, conn):
"""Get info on a list of mids"""
c = conn.cursor()
midlist = ','.join("'{}'".format(x) for x in mids)
sql = """
SELECT
mid,
name,
thumbnail,
url
FROM mid_data
WHERE
mid IN ({})
AND thumbnail IS NOT NULL
""".format(midlist)
c.execute(sql)
conn.commit()
results = c.fetchall()
c.close()
if results:
ordering = {mid: i for (i, mid) in enumerate(mids)}
columns = ['mid', 'name', 'thumbnail', 'url']
mid_data = [{c: v for c, v in zip(columns, r)} for r in results]
mid_data = sorted(mid_data, key=lambda x: ordering.get(x['mid'], 1000))
else:
mid_data = []
return mid_data


def get_recommendations(mid, conn):
"""
Grab recommendations for a single mid.
Returns multiple recommendation types as a dictionary.
Example Return
--------------
{
'l2r': [mid1, mid2, mid3],
'wrmf': [mid5, mid6, mid7
}
"""
c = conn.cursor()
sql = """
SELECT
type,
recommended
FROM recommendations
WHERE
mid = '{}'
""".format(mid)
c.execute(sql)
results = c.fetchall()
if results:
out = []
for r in results:
out.append((r[0], [str(x) for x in r[1].split(',')]))
out = dict(out)
else:
out = None
return out


def get_mid_names(conn):
"""Get small list of mids and names to seed dropdown menu."""
c = conn.cursor()
sql = 'SELECT mid, model_name from mid_names'
c.execute(sql)
results = c.fetchall()
c.close()
# Don't feel like implementing
# http://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite-query
# to make a DictCursor. Do by hand.
return [{'mid': r[0], 'model_name': r[1]} for r in results]


def parse_mid(request):
"""
Go through funky series of scenarios parsing out the mid
from the GET request.
"""
mid = request.args.get('mid')
if mid is not None:
return mid

link = request.args.get('link')
if link is None or not link:
return None

splits = link.split('/')
mid = splits[-1]

if splits[-2] != 'models':
# Link is in funny format. Nothing we can do!
return None

return mid


def load_recs(filename, N=None):
if N is not None:
N += 1
Expand Down

0 comments on commit df21f91

Please sign in to comment.