forked from bradbenjamin-wf/gae_starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
123 lines (108 loc) · 4.42 KB
/
main.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
import bottle
from bottle import route, post, get, request, error, debug, redirect, response
from jinja2 import Environment, FileSystemLoader
import logging, json
from os.path import dirname
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.api import taskqueue
from google.appengine.api import urlfetch
from payments import stripe_pay
from models import Account
JINJA_ENV = Environment(
loader=FileSystemLoader(dirname(__file__) + '/templates/'),
extensions=['jinja2.ext.autoescape'])
@route('/')
@post('/')
def home():
user = users.get_current_user()
login_url = users.create_login_url(request.path)
if not user:
return respond('home.html', {'login_url':login_url, 'user':user})
account = None
warn_msg = None
success_msg = None
account = Account.get_or_insert(user.user_id(), user_id = user.user_id())
if not account.email: # ensure this is set on account creation
account.email = user.email()
if request.forms.get('update_sites'):
site_urls = [request.forms.get('site' + str(i)) for i in range(1,6) if request.forms.get('site' + str(i))]
account.sites = site_urls
account.put()
elif request.forms.get('stripeToken'):
if account.upgraded:
logging.info("User {} attempted to pay for an already-paid account".format(user.email()))
warn_msg = "This account appears to have already paid"
else:
charge, msg = stripe_pay(500,request.forms.get('stripeToken'), user)
if charge is not None:
success_msg = msg
chargejson = {'method':'Stripe', 'id': charge.id, 'created': charge.created, 'amount':charge.amount,
'type':charge.card.type, 'balance_transaction':charge.balance_transaction,
'description':charge.description}
account.payment_info = json.dumps(chargejson)
account.upgraded = True
account.put()
else:
warn_msg = msg
return respond('home.html', {'login_url':login_url, 'user':user, 'account':account, 'warn_msg':warn_msg, 'success_msg':success_msg})
def respond(template_file, params):
tpl = JINJA_ENV.get_template(template_file)
return tpl.render(**params)
@route('/cron/site_checks')
def site_checks():
account_query = Account.query()
for account in account_query.iter():
taskqueue.add(url='/queue/site_check/{}'.format(account.user_id), params={}, method="GET")
@route('/queue/site_check/<user_id>')
def site_check(user_id):
account = Account.get_by_id(user_id)
failed_site_reports = []
for site in account.sites:
if site:
result = urlfetch.fetch(site)
if result.status_code != 200:
failed_site_reports.append("site {} failed with a {} status code".format(site, result.status_code))
if failed_site_reports:
failed_site_report = '\n'.join(failed_site_reports)
message = mail.EmailMessage()
message.sender = 'failures@gae_starter@appspotmail.com'
message.body = """Failures for your site on {}:
{}
""".format('downtime-toy.appspot.com', failed_site_report)
message.subject = "Notification of site failures"
message.to = account.email
try:
message.send()
logging.info("sent email to {} for failed sites.".format(account.email))
except:
logging.warn("failed to send owner email to {} for failed sites.".format(account.email))
else:
logging.info("no failed sites for email {}".format(account.email))
@route('/admin')
def admin_page():
if users.is_current_user_admin():
return respond('404.html', {})
accounts = Account.query().fetch(limit=100)
return respond('admin.html', {'accounts':accounts})
def main():
debug(True)
app = bottle.app()
## SESSIONS
# session_opts = {
# 'session.type': 'ext:google'
# }
# app = beaker.middleware.SessionMiddleware(bottle.app(), session_opts)
## APPSTATS
# from google.appengine.ext.appstats import recording
# app = recording.appstats_wsgi_middleware(app)
run_wsgi_app(app)
@error(403)
def error403(code):
return "I haven't handled that situation yet"
@error(404)
def error404(code):
return respond('404.html', {})
if __name__=="__main__":
main()