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,45 @@ 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+
113+ Returns:
114+ A dictionary containing information about votes.
115+ """
97116 votes = []
98117
99118 with db .connect () as conn :
100119 # 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 ()
120+ recent_votes = conn .execute (
121+ sqlalchemy .text (
122+ "SELECT candidate, time_cast FROM votes ORDER BY time_cast DESC LIMIT 5"
123+ )
124+ ).fetchall ()
104125 # Convert the results into a list of dicts representing votes
105126 for row in recent_votes :
106127 votes .append ({"candidate" : row [0 ], "time_cast" : row [1 ]})
@@ -122,6 +143,15 @@ def get_index_context(db: sqlalchemy.engine.base.Engine) -> dict:
122143
123144# save_vote saves a vote to the database that was retrieved from form data
124145def save_vote (db : sqlalchemy .engine .base .Engine , team : str ) -> Response :
146+ """Saves a single vote into the database.
147+
148+ Args:
149+ db: Connection to the database.
150+ team: The identifier of a team the vote is casted on.
151+
152+ Returns:
153+ A HTTP response that can be sent to the client.
154+ """
125155 time_cast = datetime .datetime .now (tz = datetime .timezone .utc )
126156 # Verify that the team is one of the allowed options
127157 if team != "TABS" and team != "SPACES" :
0 commit comments