-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
213 lines (184 loc) · 6.17 KB
/
app.py
File metadata and controls
213 lines (184 loc) · 6.17 KB
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
"""
Server for ethiclo
"""
import os
from flask import Flask, request, jsonify, render_template
import psycopg2 as pg
from flask_cors import CORS
# from dotenv import load_dotenv
from helpers import handle_url
from scraper import sustainability_search
from models.scoring.scoring_classes import predict_sustainability
# load_dotenv()
# Initialize flask app
app = Flask(__name__)
CORS(app)
# Base route for testing
@app.route('/')
def healthcheck():
"""Healthcheck entrypoint.
"""
return jsonify({'status': 200})
@app.route('/add_shopper/<string:email>', methods=["POST"])
def add_shopper(email: str):
"""Add a shopper to the db.
"""
# Connect to the db
conn = connect()
cur = conn.cursor()
print("Connected to db")
# Insert the user into the db
try:
insert = "INSERT INTO Shopper (email) VALUES (%s)"
cur.execute(insert, [email])
conn.commit()
cur.close()
conn.close()
return jsonify({'status': 200})
except pg.Error:
cur.close()
conn.close()
return jsonify({'status': 400, 'error': pg.Error})
@app.route('/get_my_products/<string:email>', methods=["POST"])
def get_my_products(email: str):
# Connect to the db
conn = connect()
cur = conn.cursor()
print("Connected to db")
# Insert the user into the db
try:
products = "SELECT * FROM Product WHERE shopper = %s AND alt_to = 0"
cur.execute(products, [email])
resp = cur.fetchall()
cur.close()
conn.close()
# print(jsonify(resp))
prod = []
for product in resp:
new = {}
new['id'] = product[0]
new['url'] = product[1]
new['img_src'] = product[2]
new['title'] = product[3]
new['price'] = product[4]
new['brand'] = product[5]
new['description'] = product[6]
new['score'] = product[7]
prod.append(new)
print(prod)
cur.close()
conn.close()
return jsonify(prod)
except pg.Error:
cur.close()
conn.close()
return jsonify({'status': 400, 'error': pg.Error})
@app.route('/add_url', methods=["POST"])
def add_url():
"""Send a URL to the db.
"""
# Get the data from the request
data = request.get_json()
url = data['url']
email = data['email']
# Connect to the db
conn = connect()
cur = conn.cursor()
# Insert the url into the db
try:
insert = "INSERT INTO Website (url, shopper) VALUES (%s, %s);"
cur.execute(insert, [url, email])
conn.commit()
# TODO: Call helper function
data = handle_url(url)
# insert the product into the db
insert_product = """
INSERT INTO Product (url, img_src, title, price, brand, description, score, alt_to, shopper)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s);
"""
cur.execute(insert_product, [data['url'], data['image'], data['title'],
float(data['price'][1:]), data['brand'],
'description', data['score'], 0, email])
conn.commit()
# Get the product id
get_product_id = """
SELECT product_id FROM Product
WHERE url = %s AND shopper = %s;
"""
cur.execute(get_product_id, [data['url'], email])
product_id = cur.fetchone()[0]
# make the query
query = f"{data['classification']} {data['title'].lower().replace(data['brand'].lower(), '')}"
print(f"This is the query: {query}\n\n\n")
sustainable_items = sustainability_search(query)
for item in sustainable_items:
# TODO: score the item
text = [f"{sustainable_items[item]['brand']} {sustainable_items[item]['title']}"]
predictions = predict_sustainability(text)
score = predictions.tolist()
cur.execute(insert_product, [sustainable_items[item]['url'], sustainable_items[item]['img'], sustainable_items[item]['title'],
float(sustainable_items[item]['price'][1:]), sustainable_items[item]['brand'],
sustainable_items[item]['description'], score, product_id, email])
conn.commit()
cur.close()
conn.close()
return jsonify({'status': 200})
except pg.Error:
cur.close()
conn.close()
return jsonify({'status': 400, 'error': pg.Error})
@app.route('/get_sustainable_products', methods=["POST"])
def get_sustainable_products():
"""Fetch sustainable alternatives from the database
"""
data = request.get_json()
url = data['url']
email = data['email']
# Get the sustainable alternatives from the db
get_sustainable_products = """
SELECT * FROM Product
WHERE alt_to IN (
SELECT product_id FROM Product
WHERE url = %s AND shopper = %s
);
"""
conn = connect()
cur = conn.cursor()
try:
cur.execute(get_sustainable_products, [url, email])
resp = cur.fetchall()
prod = []
for product in resp:
new = {}
new['id'] = product[0]
new['url'] = product[1]
new['img_src'] = product[2]
new['title'] = product[3]
new['price'] = product[4]
new['brand'] = product[5]
new['description'] = product[6]
new['score'] = product[7]
prod.append(new)
print(prod)
cur.close()
conn.close()
total = len(prod)
return jsonify(prod[total - int(total /2):])
except pg.Error:
cur.close()
conn.close()
return jsonify({'status': 400, 'error': pg.Error})
def connect():
"""Connect to the db.
"""
try:
connection = pg.connect(
dbname=os.environ["PGDATABASE"], user=os.environ["PGUSER"],
password=os.environ["PASSWORD"],
options="-c search_path=ethiclo"
)
return connection
except pg.Error:
return None
if __name__ == '__main__':
app.run(debug=True, port=os.getenv("PORT", default=5000))