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