-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhelpers.py
154 lines (135 loc) · 5.06 KB
/
helpers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import os
import requests
import sqlite3
import numpy as np
from flask import redirect, session, request
from functools import wraps
from typing import Any, List
# From CS50 pset9 Finance #######################################################
def login_required(f):
"""
Decorate routes to require login.
https://flask.palletsprojects.com/en/1.1.x/patterns/viewdecorators/
"""
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function
# Functions ###############################################################
def database(db="recifilter.db"):
con = sqlite3.connect(db)
cur = con.cursor()
return con, cur
def split_dict(dct, sections):
lst = sorted(list(dct.items()))
split_lst = np.array_split(lst, sections)
splitted = []
for i in range(sections):
sec_i = split_lst[i]
splitted.append(dict(sec_i))
return splitted
def stringify(list_name, string):
list = request.args.getlist(list_name)
arr = []
for l in list:
arr.append(string + l)
stringified = "".join(arr)
return list, stringified
def lookup(param):
try:
api_key = os.environ.get("API_KEY")
api_id = os.environ.get("API_ID")
response = requests.get(
f"https://api.edamam.com/api/recipes/v2?type=public&app_id={api_id}&app_key={api_key}&q={param}")
response.raise_for_status()
except requests.RequestException:
return None
try:
result = response.json()
# count = result["count"]
# next = result["_links"]["next"]["href"]
hits_dict = result["hits"]
recipes_list = []
for index in hits_dict:
link = index["_links"]["self"]["href"] # Recipe's JSON link
label = index["recipe"]["label"]
image = index["recipe"]["image"]
source = index["recipe"]["source"]
url = index["recipe"]["url"] # Source link
dietLabels = list(index["recipe"]["dietLabels"])
healthLabels = list(index["recipe"]["healthLabels"])
ingredientLines = list(index["recipe"]["ingredientLines"])
calories = index["recipe"]["calories"]
totalTime = index["recipe"]["totalTime"]
cuisineType = list(index["recipe"]["cuisineType"])
dishType = list(index["recipe"]["dishType"])
recipes_list.append(
{
"link": link,
"label": label,
"image": image,
"source": source,
"url": url,
"dietLabels": dietLabels,
"healthLabels": healthLabels,
"ingredientLines": ingredientLines,
"calories": calories,
"totalTime": totalTime,
"cuisineType": cuisineType,
"dishType": dishType
})
return recipes_list # , next, count
except (KeyError, TypeError, ValueError):
return None
def readable_list(seq: List[Any]) -> str:
"""
Grammatically correct human readable string from list (with Oxford comma)
https://stackoverflow.com/a/53981846/19845029
"""
seq = [str(s) for s in seq]
if len(seq) < 3:
return ' and '.join(seq)
return ', '.join(seq[:-1]) + ', and ' + seq[-1]
# def lookup_recipe(link):
# try:
# response = requests.get(link)
# response.raise_for_status()
# except requests.RequestException:
# return None
# try:
# result = response.json()
# print(type(result)) # dict
# recipe_info = []
# for key in result:
# link = key["_links"]["self"]["href"]
# label = key["recipe"]["label"]
# image = key["recipe"]["image"]
# source = key["recipe"]["source"]
# url = key["recipe"]["url"]
# dietLabels = list(key["recipe"]["dietLabels"])
# healthLabels = list(key["recipe"]["healthLabels"])
# ingredientLines = list(key["recipe"]["ingredientLines"])
# calories = key["recipe"]["calories"]
# totalTime = key["recipe"]["totalTime"]
# cuisineType = key["recipe"]["cuisineType"]
# dishType = key["recipe"]["dishType"]
# recipe_info.append(
# {
# "link": link,
# "label": label,
# "image": image,
# "source": source,
# "url": url,
# "dietLabels": dietLabels,
# "healthLabels": healthLabels,
# "ingredientLines": ingredientLines,
# "calories": calories,
# "totalTime": totalTime,
# "cuisineType": cuisineType,
# "dishType": dishType
# })
# return recipe_info
# except (KeyError, TypeError, ValueError):
# return None