-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
74 lines (54 loc) · 2.02 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
#!/usr/bin/env/python
"""Main handlers module for guestbook sample with Cloud SQL"""
__author__ = '[email protected] (Takashi Matsuo)'
# standard libraries
import os
# App Engine libraries
import jinja2
import webapp2
from google.appengine.api import rdbms
# App specific libraries
import settings
class GetConnection():
"""A guard class for ensuring the connection will be closed."""
def __init__(self):
self.conn = None
def __enter__(self):
self.conn = rdbms.connect(instance=settings.CLOUDSQL_INSTANCE,
database=settings.DATABASE_NAME,
user=settings.USER_NAME,
password=settings.PASSWORD, charset='utf8')
return self.conn
def __exit__(self, type, value, traceback):
self.conn.close()
jinja2_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__))))
class MainHandler(webapp2.RequestHandler):
def get(self):
# Viewing guestbook
with GetConnection() as conn:
cursor = conn.cursor()
cursor.execute('SELECT guest_name, content, created_at FROM entries'
' ORDER BY created_at DESC limit 20')
rows = cursor.fetchall()
template_values = {'rows': rows}
template = jinja2_env.get_template('index.html')
self.response.out.write(template.render(template_values))
class GuestBook(webapp2.RequestHandler):
def post(self):
# Posting a new guestbook entry
with GetConnection() as conn:
cursor = conn.cursor()
cursor.execute('INSERT INTO entries (guest_name, content) '
'VALUES (%s, %s)',
(self.request.get('guest_name'),
self.request.get('content')))
conn.commit()
self.redirect('/')
application = webapp2.WSGIApplication(
[
('/', MainHandler),
('/sign', GuestBook),
],
debug=True
)