-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
70 lines (56 loc) · 2.19 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
import time
import redis
import json
import requests
import os
from flask import Flask, render_template, request
import config as config
application = Flask(__name__)
# cache = redis.Redis(host=config.REDIS_URL, port=6379)
cache = redis.from_url(os.environ.get("REDIS_URL"))
def process(email):
url = "https://api.sendgrid.com/v3/contactdb/recipients"
headers = {
'Content-type': 'application/json',
'Authorization': 'Bearer ' + config.SENDGRID_TOKEN
}
body = [{'email': email}]
r = requests.post(url, headers=headers, json=body)
recipient = None
if r.status_code is not 201:
print('Invalid response')
else:
print('Found email added or discovered')
data = json.loads(r.text)
if 'persisted_recipients' in data.keys() and len(data['persisted_recipients']) > 0:
recipient = data['persisted_recipients'][0]#.decode('utf-8')
if recipient is not None:
url = "https://api.sendgrid.com/v3/contactdb/lists/{}/recipients/{}".format(config.NEW_LIST, recipient)
r = requests.post(url, headers=headers, json=body)
if r.status_code is not 201:
print('Error adding {} to list {}'.format(email, config.NEW_LIST))
else:
print('Adding {} to list {}'.format(email, config.NEW_LIST))
url = "https://api.sendgrid.com/v3/contactdb/lists/{}/recipients/{}".format(config.OLD_LIST, recipient)
r = requests.delete(url, headers=headers, json=body)
if r.status_code is not 201:
print('Error deleting {} from list {}'.format(email, config.OLD_LIST))
else:
print('Deleting {} from list {}'.format(email, config.OLD_LIST))
@application.route("/")
def index():
email = request.args.get('email')
if email is None:
print('No email')
else:
val = cache.get(email)
if val is None:
cache.set(email, time.time())
print('Importing email to lists')
process(email)
else:
print('{} already processed'.format(email))
email = None
return render_template('./index.html', email=email)
if __name__ == "__main__":
application.run(host='0.0.0.0')