Skip to content

Commit 0deb8c9

Browse files
author
Jon Wayne Parrott
authored
Fork cloud sql sample into a separate postgres sample (#1025)
1 parent 985c2be commit 0deb8c9

File tree

6 files changed

+180
-1
lines changed

6 files changed

+180
-1
lines changed

appengine/flexible/cloudsql/requirements.txt

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,3 @@ Flask==0.12.2
22
Flask-SQLAlchemy==2.2
33
gunicorn==19.7.1
44
PyMySQL==0.7.11
5-
psycopg2==2.7.1
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
runtime: python
2+
env: flex
3+
entrypoint: gunicorn -b :$PORT main:app
4+
5+
runtime_config:
6+
python_version: 3
7+
8+
#[START env]
9+
env_variables:
10+
# Replace user, password, database, and instance connection name with the values obtained
11+
# when configuring your Cloud SQL instance.
12+
SQLALCHEMY_DATABASE_URI: >-
13+
postgresql+psycopg2://USER:PASSWORD@/DATABASE?host=/cloudsql/INSTANCE_CONNECTION_NAME
14+
#[END env]
15+
16+
#[START cloudsql_settings]
17+
# Replace project and instance with the values obtained when configuring your
18+
# Cloud SQL instance.
19+
beta_settings:
20+
cloud_sql_instances: INSTANCE_CONNECTION_NAME
21+
#[END cloudsql_settings]
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#! /usr/bin/env python
2+
# Copyright 2015 Google Inc. All Rights Reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
# [START all]
17+
18+
from main import db
19+
20+
21+
if __name__ == '__main__':
22+
print('Creating all database tables...')
23+
db.create_all()
24+
print('Done!')
25+
# [END all]
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# Copyright 2015 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""This sample shows how to connect to PostgreSQL running on Cloud SQL.
16+
17+
See the documentation for details on how to setup and use this sample:
18+
https://cloud.google.com/appengine/docs/flexible/python\
19+
/using-cloud-sql-postgres
20+
"""
21+
22+
import datetime
23+
import logging
24+
import os
25+
import socket
26+
27+
from flask import Flask, request
28+
from flask_sqlalchemy import SQLAlchemy
29+
import sqlalchemy
30+
31+
32+
app = Flask(__name__)
33+
34+
35+
def is_ipv6(addr):
36+
"""Checks if a given address is an IPv6 address."""
37+
try:
38+
socket.inet_pton(socket.AF_INET6, addr)
39+
return True
40+
except socket.error:
41+
return False
42+
43+
44+
# [START example]
45+
# Environment variables are defined in app.yaml.
46+
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']
47+
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
48+
49+
db = SQLAlchemy(app)
50+
51+
52+
class Visit(db.Model):
53+
id = db.Column(db.Integer, primary_key=True)
54+
timestamp = db.Column(db.DateTime())
55+
user_ip = db.Column(db.String(46))
56+
57+
def __init__(self, timestamp, user_ip):
58+
self.timestamp = timestamp
59+
self.user_ip = user_ip
60+
61+
62+
@app.route('/')
63+
def index():
64+
user_ip = request.remote_addr
65+
66+
# Keep only the first two octets of the IP address.
67+
if is_ipv6(user_ip):
68+
user_ip = ':'.join(user_ip.split(':')[:2])
69+
else:
70+
user_ip = '.'.join(user_ip.split('.')[:2])
71+
72+
visit = Visit(
73+
user_ip=user_ip,
74+
timestamp=datetime.datetime.utcnow()
75+
)
76+
77+
db.session.add(visit)
78+
db.session.commit()
79+
80+
visits = Visit.query.order_by(sqlalchemy.desc(Visit.timestamp)).limit(10)
81+
82+
results = [
83+
'Time: {} Addr: {}'.format(x.timestamp, x.user_ip)
84+
for x in visits]
85+
86+
output = 'Last 10 visits:\n{}'.format('\n'.join(results))
87+
88+
return output, 200, {'Content-Type': 'text/plain; charset=utf-8'}
89+
# [END example]
90+
91+
92+
@app.errorhandler(500)
93+
def server_error(e):
94+
logging.exception('An error occurred during a request.')
95+
return """
96+
An internal error occurred: <pre>{}</pre>
97+
See logs for full stacktrace.
98+
""".format(e), 500
99+
100+
101+
if __name__ == '__main__':
102+
# This is used when running locally. Gunicorn is used to run the
103+
# application on Google App Engine. See entrypoint in app.yaml.
104+
app.run(host='127.0.0.1', port=8080, debug=True)
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Copyright 2015 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import main
16+
17+
18+
def test_index():
19+
main.db.create_all()
20+
21+
main.app.testing = True
22+
client = main.app.test_client()
23+
24+
r = client.get('/', environ_base={'REMOTE_ADDR': '127.0.0.1'})
25+
assert r.status_code == 200
26+
assert '127.0' in r.data.decode('utf-8')
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Flask==0.12.2
2+
Flask-SQLAlchemy==2.2
3+
gunicorn==19.7.1
4+
psycopg2==2.7.1

0 commit comments

Comments
 (0)