forked from soumoks/caring-companion-v2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
149 lines (133 loc) · 5.48 KB
/
app.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
from flask import Flask
from flask_cors import CORS,cross_origin
from flask import jsonify,request
from pymongo import MongoClient
from bson.objectid import ObjectId
from pprint import pprint
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
import os
import json
#Extending JSONencoder to support Object_ID returned by MongoDB
#https://stackoverflow.com/questions/16586180/typeerror-objectid-is-not-json-serializable
"""
Referenced from
https://medium.com/@riken.mehta/full-stack-tutorial-flask-react-docker-ee316a46e876
"""
class JSONEncoder(json.JSONEncoder):
''' extend json-encoder class'''
def default(self, o):
if isinstance(o, ObjectId):
return str(o)
if isinstance(o, datetime.datetime):
return str(o)
return json.JSONEncoder.default(self, o)
app = Flask(__name__)
app.json_encoder = JSONEncoder
@app.route("/")
def hello_world():
return jsonify(s1.__dict__)
"""
Get all citizens present in the DB
"""
@app.route("/getcitizens")
@cross_origin()
def get_citizens():
new_list = [post for post in posts.find()]
return jsonify(new_list)
"""
Create citizens in the DB
"""
@app.route("/putcitizen",methods=['POST'])
def create_citizen():
if request.method == 'POST':
data = request.get_json(force=True,cache=False)
pprint(data)
return jsonify({'ok': True, 'message': 'User created successfully!'}), 200
"""
Get citizens that have more than 50% match in interests
"""
@app.route("/getmatchingcitizens")
@cross_origin()
def get_matching_citizens():
volunteer = request.headers.get('X-volunteer')
vaibhav_interests = ['sleeping','home building','garden walks']
arsalan_interests = ['music','politics','science','reading']
senior_list = [post for post in posts.find()]
if request.headers['X-volunteer'] == "Vaibhav":
dummy_volunteer_interest_list = vaibhav_interests
matching_list = []
for senior in senior_list:
match = len(set(dummy_volunteer_interest_list) & set(senior['interests'])) / float(len(set(dummy_volunteer_interest_list) | set(senior['interests']))) * 100
if match >= 20:
matching_list.append(senior)
if len(matching_list) == 0:
return(jsonify("No matches found!"))
elif request.headers['X-volunteer'] == "Arsalan":
dummy_volunteer_interest_list = arsalan_interests
matching_list = []
senior_list = [post for post in posts.find()]
for senior in senior_list:
match = len(set(dummy_volunteer_interest_list) & set(senior['interests'])) / float(len(set(dummy_volunteer_interest_list) | set(senior['interests']))) * 100
if match >= 20:
matching_list.append(senior)
if len(matching_list) == 0:
return jsonify("No matches found!")
else:
return jsonify("Send a valid user header!")
return jsonify(matching_list)
@app.route("/sendemail", methods = ["POST"])
@cross_origin()
def send_email():
sendgrid_api_key = os.environ.get('SENDGRID_API_KEY')
if request.method == 'POST':
"""The returned data will be in the following format:
{
volunteer_name: "name",
senior_citizen: {Senior object},
volunteer_email: "email"
time_slot: "chosen time slot"
}
"""
data = request.get_json(force=True,cache=False)
#data = data.__dict__
if data is not None:
vol_email = str(data.get("volunteer_email"))
vol_name = str(data.get("volunteer_name"))
senior_name = str(data.get('senior_citizen').get('name'))
time_slot = str(data.get('time_slot'))
vol_content = "You have requested to visit "+ senior_name+" at a timeslot of "+time_slot+". \n Thank you for your interest and we will get back to you."
home_content = vol_name+' whose email is: '+vol_email+' has requested to be a Caring Companion for '+ senior_name+'.\n The time slot requested is: '+ time_slot+'.\n '+ vol_name+' is awaiting your response!'
messag_to_vol = Mail(
from_email='email@em4748.sourabh.org',
to_emails=vol_email,
subject='Thank you for requesting to be a Caring Companion!',
html_content=vol_content)
messag_to_home = Mail(
from_email='email@em4748.sourabh.org',
to_emails='thanmayee.mudigonda@gmail.com',
subject=vol_name+' has requested to be a Caring Companion!',
html_content=home_content)
try:
sg = SendGridAPIClient(sendgrid_api_key)
response_to_vol = sg.send(messag_to_vol)
response_to_home = sg.send(messag_to_home)
print(response_to_vol.status_code)
print(response_to_vol.body)
print(response_to_vol.headers)
print(response_to_home.status_code)
print(response_to_home.body)
print(response_to_home.headers)
except Exception as e:
print(e.message)
return jsonify({'ok': True, 'message': 'Email sent successfully!'}), 200
else:
return jsonify({'ok': False, 'message': 'Bad request parameters!'}), 400
if __name__ == "__main__":
client = MongoClient('localhost', 27017)
print("Connected to MongoDB..")
#Choose Database citizens
db = client.Citizens
#Choose collections posts
posts = db.posts
app.run(port=80)