3333
3434
3535def init_connection_pool () -> sqlalchemy .engine .base .Engine :
36+ """Sets up connection pool for the app."""
3637 # use a TCP socket when INSTANCE_HOST (e.g. 127.0.0.1) is defined
3738 if os .environ .get ("INSTANCE_HOST" ):
3839 return connect_tcp_socket ()
@@ -45,7 +46,11 @@ def init_connection_pool() -> sqlalchemy.engine.base.Engine:
4546 if os .environ .get ("INSTANCE_CONNECTION_NAME" ):
4647 # Either a DB_USER or a DB_IAM_USER should be defined. If both are
4748 # defined, DB_IAM_USER takes precedence.
48- return connect_with_connector_auto_iam_authn () if os .environ .get ("DB_IAM_USER" ) else connect_with_connector ()
49+ return (
50+ connect_with_connector_auto_iam_authn ()
51+ if os .environ .get ("DB_IAM_USER" )
52+ else connect_with_connector ()
53+ )
4954
5055 raise ValueError (
5156 "Missing database connection type. Please define one of INSTANCE_HOST, INSTANCE_UNIX_SOCKET, or INSTANCE_CONNECTION_NAME"
@@ -54,12 +59,15 @@ def init_connection_pool() -> sqlalchemy.engine.base.Engine:
5459
5560# create 'votes' table in database if it does not already exist
5661def migrate_db (db : sqlalchemy .engine .base .Engine ) -> None :
62+ """Creates the `votes` table if it doesn't exist."""
5763 with db .connect () as conn :
58- conn .execute (sqlalchemy .text (
59- "CREATE TABLE IF NOT EXISTS votes "
60- "( vote_id SERIAL NOT NULL, time_cast timestamp NOT NULL, "
61- "candidate VARCHAR(6) NOT NULL, PRIMARY KEY (vote_id) );"
62- ))
64+ conn .execute (
65+ sqlalchemy .text (
66+ "CREATE TABLE IF NOT EXISTS votes "
67+ "( vote_id SERIAL NOT NULL, time_cast timestamp NOT NULL, "
68+ "candidate VARCHAR(6) NOT NULL, PRIMARY KEY (vote_id) );"
69+ )
70+ )
6371 conn .commit ()
6472
6573
@@ -75,32 +83,44 @@ def migrate_db(db: sqlalchemy.engine.base.Engine) -> None:
7583# as the function is loaded. This is primarily to help testing.
7684@app .before_first_request
7785def init_db () -> sqlalchemy .engine .base .Engine :
86+ """Initiates connection to database and its structure."""
7887 global db
7988 db = init_connection_pool ()
8089 migrate_db (db )
8190
8291
8392@app .route ("/" , methods = ["GET" ])
8493def render_index () -> str :
94+ """Serves the index page of the app."""
8595 context = get_index_context (db )
8696 return render_template ("index.html" , ** context )
8797
8898
8999@app .route ("/votes" , methods = ["POST" ])
90100def cast_vote () -> Response :
91- team = request .form ['team' ]
101+ """Processes a single vote from user."""
102+ team = request .form ["team" ]
92103 return save_vote (db , team )
93104
94105
95106# get_index_context gets data required for rendering HTML application
96107def get_index_context (db : sqlalchemy .engine .base .Engine ) -> dict :
108+ """Retrieves data from the database about the votes.
109+
110+ Args:
111+ db: Connection to the database.
112+ Returns:
113+ A dictionary containing information about votes.
114+ """
97115 votes = []
98116
99117 with db .connect () as conn :
100118 # Execute the query and fetch all results
101- recent_votes = conn .execute (sqlalchemy .text (
102- "SELECT candidate, time_cast FROM votes ORDER BY time_cast DESC LIMIT 5"
103- )).fetchall ()
119+ recent_votes = conn .execute (
120+ sqlalchemy .text (
121+ "SELECT candidate, time_cast FROM votes ORDER BY time_cast DESC LIMIT 5"
122+ )
123+ ).fetchall ()
104124 # Convert the results into a list of dicts representing votes
105125 for row in recent_votes :
106126 votes .append ({"candidate" : row [0 ], "time_cast" : row [1 ]})
@@ -122,6 +142,14 @@ def get_index_context(db: sqlalchemy.engine.base.Engine) -> dict:
122142
123143# save_vote saves a vote to the database that was retrieved from form data
124144def save_vote (db : sqlalchemy .engine .base .Engine , team : str ) -> Response :
145+ """Saves a single vote into the database.
146+
147+ Args:
148+ db: Connection to the database.
149+ team: The identifier of a team the vote is cast on.
150+ Returns:
151+ A HTTP response that can be sent to the client.
152+ """
125153 time_cast = datetime .datetime .now (tz = datetime .timezone .utc )
126154 # Verify that the team is one of the allowed options
127155 if team != "TABS" and team != "SPACES" :
0 commit comments