forked from googlearchive/cloud-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
81 lines (64 loc) · 2.48 KB
/
Copy pathmain.py
File metadata and controls
81 lines (64 loc) · 2.48 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
"""
To create the intial database, follow the setup instructions:
https://developers.google.com/appengine/training/cloud-sql/deploy_the_app
At a minimum:
create database guestbook charset utf8;
use guestbook;
create TABLE entries (id int not null auto_increment primary key,
guest_name varchar(255),
content varchar(255),
created_at timestamp)
DEFAULT CHARSET=utf8;
"""
import os
import logging
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import rdbms
import jinja2
template_path = os.path.join(os.path.dirname(__file__))
jinja2_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(template_path)
)
# Assume Cloud SQL instance name matches app id
APP_ID = app_identity.get_application_id()
CLOUDSQL_INSTANCE = '{}:{}'.format(APP_ID, APP_ID)
# To create the intial database, follow the setup instructions
# https://developers.google.com/appengine/training/cloud-sql/deploy_the_app
DATABASE_NAME = 'guestbook'
USER_NAME = None #'username'
PASSWORD = None #'password'
def get_connection():
if os.environ['SERVER_SOFTWARE'].startswith('Development/'):
return rdbms.connect(instance=CLOUDSQL_INSTANCE, database=DATABASE_NAME)
else:
return rdbms.connect(instance=CLOUDSQL_INSTANCE, database=DATABASE_NAME,
user=USER_NAME, password=PASSWORD, charset='utf8')
class MainHandler(webapp2.RequestHandler):
def get(self):
# Viewing guestbook
conn = get_connection()
cursor = conn.cursor()
cursor.execute('SELECT guest_name, content, created_at FROM entries '
'ORDER BY created_at DESC limit 20')
rows = cursor.fetchall()
conn.close()
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
conn = get_connection()
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()
conn.close()
self.redirect("/")
application = webapp2.WSGIApplication([
("/", MainHandler),
("/sign", GuestBook),
], debug=True)