|
| 1 | +# Copyright 2018 Google LLC |
| 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 datetime |
| 16 | +import logging |
| 17 | +import os |
| 18 | + |
| 19 | +from flask import Flask, render_template, request, Response |
| 20 | +import sqlalchemy |
| 21 | + |
| 22 | + |
| 23 | +# Remember - storing secrets in plaintext is potentially unsafe. Consider using |
| 24 | +# something like https://cloud.google.com/kms/ to help keep secrets secret. |
| 25 | +db_user = os.environ.get("DB_USER") |
| 26 | +db_pass = os.environ.get("DB_PASS") |
| 27 | +db_name = os.environ.get("DB_NAME") |
| 28 | +cloud_sql_instance_name = os.environ.get("CLOUD_SQL_INSTANCE_NAME") |
| 29 | + |
| 30 | +app = Flask(__name__) |
| 31 | + |
| 32 | +logger = logging.getLogger() |
| 33 | + |
| 34 | +# [START cloud_sql_mysql_connection_pool] |
| 35 | +# The SQLAlchemy engine will help manage interactions, including automatically |
| 36 | +# managing a pool of connections to your database |
| 37 | +db = sqlalchemy.create_engine( |
| 38 | + # Equivalent URL: |
| 39 | + # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=/cloudsql/<cloud_sql_instance_name> |
| 40 | + sqlalchemy.engine.url.URL( |
| 41 | + drivername='mysql+pymysql', |
| 42 | + username=db_user, |
| 43 | + password=db_pass, |
| 44 | + database=db_name, |
| 45 | + query={ |
| 46 | + 'unix_socket': '/cloudsql/{}'.format(cloud_sql_instance_name) |
| 47 | + } |
| 48 | + ), |
| 49 | + # ... Specify additional properties here. |
| 50 | + # [START_EXCLUDE] |
| 51 | + |
| 52 | + # [START cloud_sql_mysql_limit_connections] |
| 53 | + # Pool size is the maximum number of permanent connections to keep. |
| 54 | + pool_size=5, |
| 55 | + # Temporarily exceeds the set pool_size if no connections are available. |
| 56 | + max_overflow=2, |
| 57 | + # The total number of concurrent connections for your application will be |
| 58 | + # a total of pool_size and max_overflow. |
| 59 | + # [END cloud_sql_mysql_limit_connections] |
| 60 | + |
| 61 | + # [START cloud_sql_mysql_connection_backoff] |
| 62 | + # SQLAlchemy automatically uses delays between failed connection attempts, |
| 63 | + # but provides no arguments for configuration. |
| 64 | + # [END cloud_sql_mysql_connection_backoff] |
| 65 | + |
| 66 | + # [START cloud_sql_mysql_connection_timeout] |
| 67 | + # 'pool_timeout' is the maximum number of seconds to wait when retrieving a |
| 68 | + # new connection from the pool. After the specified amount of time, an |
| 69 | + # exception will be thrown. |
| 70 | + pool_timeout=30, # 30 seconds |
| 71 | + # [END cloud_sql_mysql_connection_timeout] |
| 72 | + |
| 73 | + # [START cloud_sql_mysql_connection_lifetime] |
| 74 | + # 'pool_recycle' is the maximum number of seconds a connection can persist. |
| 75 | + # Connections that live longer than the specified amount of time will be |
| 76 | + # reestablished |
| 77 | + pool_recycle=1800, # 30 minutes |
| 78 | + # [END cloud_sql_mysql_connection_lifetime] |
| 79 | + |
| 80 | + # [END_EXCLUDE] |
| 81 | +) |
| 82 | +# [END cloud_sql_mysql_connection_pool] |
| 83 | + |
| 84 | + |
| 85 | +@app.before_first_request |
| 86 | +def create_tables(): |
| 87 | + # Create tables (if they don't already exist) |
| 88 | + with db.connect() as conn: |
| 89 | + conn.execute( |
| 90 | + "CREATE TABLE IF NOT EXISTS votes " |
| 91 | + "( vote_id SERIAL NOT NULL, time_cast timestamp NOT NULL, " |
| 92 | + "candidate CHAR(6) NOT NULL, PRIMARY KEY (vote_id) );" |
| 93 | + ) |
| 94 | + |
| 95 | + |
| 96 | +@app.route('/', methods=['GET']) |
| 97 | +def index(): |
| 98 | + votes = [] |
| 99 | + with db.connect() as conn: |
| 100 | + # Execute the query and fetch all results |
| 101 | + recent_votes = conn.execute( |
| 102 | + "SELECT candidate, time_cast FROM votes " |
| 103 | + "ORDER BY time_cast DESC LIMIT 5" |
| 104 | + ).fetchall() |
| 105 | + # Convert the results into a list of dicts representing votes |
| 106 | + for row in recent_votes: |
| 107 | + votes.append({ |
| 108 | + 'candidate': row[0], |
| 109 | + 'time_cast': row[1] |
| 110 | + }) |
| 111 | + |
| 112 | + stmt = sqlalchemy.text( |
| 113 | + "SELECT COUNT(vote_id) FROM votes WHERE candidate=:candidate") |
| 114 | + # Count number of votes for tabs |
| 115 | + tab_result = conn.execute(stmt, candidate="TABS").fetchone() |
| 116 | + tab_count = tab_result[0] |
| 117 | + # Count number of votes for spaces |
| 118 | + space_result = conn.execute(stmt, candidate="SPACES").fetchone() |
| 119 | + space_count = space_result[0] |
| 120 | + |
| 121 | + return render_template( |
| 122 | + 'index.html', |
| 123 | + recent_votes=votes, |
| 124 | + tab_count=tab_count, |
| 125 | + space_count=space_count |
| 126 | + ) |
| 127 | + |
| 128 | + |
| 129 | +@app.route('/', methods=['POST']) |
| 130 | +def save_vote(): |
| 131 | + # Get the team and time the vote was cast. |
| 132 | + team = request.form['team'] |
| 133 | + time_cast = datetime.datetime.utcnow() |
| 134 | + # Verify that the team is one of the allowed options |
| 135 | + if team != "TABS" and team != "SPACES": |
| 136 | + logger.warning(team) |
| 137 | + return Response( |
| 138 | + response="Invalid team specified.", |
| 139 | + status=400 |
| 140 | + ) |
| 141 | + |
| 142 | + # [START cloud_sql_mysql_example_statement] |
| 143 | + # Preparing a statement before hand can help protect against injections. |
| 144 | + stmt = sqlalchemy.text( |
| 145 | + "INSERT INTO votes (time_cast, candidate)" |
| 146 | + " VALUES (:time_cast, :candidate)" |
| 147 | + ) |
| 148 | + try: |
| 149 | + # Using a with statement ensures that the connection is always released |
| 150 | + # back into the pool at the end of statement (even if an error occurs) |
| 151 | + with db.connect() as conn: |
| 152 | + conn.execute(stmt, time_cast=time_cast, candidate=team) |
| 153 | + except Exception as e: |
| 154 | + # If something goes wrong, handle the error in this section. This might |
| 155 | + # involve retrying or adjusting parameters depending on the situation. |
| 156 | + # [START_EXCLUDE] |
| 157 | + logger.exception(e) |
| 158 | + return Response( |
| 159 | + status=500, |
| 160 | + response="Unable to successfully cast vote! Please check the " |
| 161 | + "application logs for more details." |
| 162 | + ) |
| 163 | + # [END_EXCLUDE] |
| 164 | + # [END cloud_sql_mysql_example_statement] |
| 165 | + |
| 166 | + return Response( |
| 167 | + status=200, |
| 168 | + response="Vote successfully cast for '{}' at time {}!".format( |
| 169 | + team, time_cast) |
| 170 | + ) |
| 171 | + |
| 172 | + |
| 173 | +if __name__ == '__main__': |
| 174 | + app.run(host='127.0.0.1', port=8080, debug=True) |
0 commit comments