#!/usr/bin/env python3 """ This module provides a set of reuseable utility functions This is a Google style docstring by the way. Read more about them here: https://www.python.org/dev/peps/pep-0257/ """ # import the mysql connector API import mysql.connector def db_connect( config ): """ Creates a connection with a MySQL database Returns a connection object (handle to the database) """ try: cnx = mysql.connector.connect( user=config['DB_USER'], password=config['DB_PASS'], host=config['DB_HOST'], database=config['DB_NAME'] ) return cnx except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print( "Something is wrong with your user name or password" ) elif err.errno == errorcode.ER_BAD_DB_ERROR: print( "Database does not exist" ) else: print(err) else: cnx.close() def render_template( temp_path, data=[] ): """ Reads in an HTML string from file replacing any placeholders with values supplied in data list. Input params: temp_path: the path to the template file data: optional list of data values Returns: String: A formatted string of HTML """ try: # open and read the template file with open(temp_path, 'r') as f: html = f.read() except: raise Exception("Could not open template") else: if data is not None: try: # replace placeholders with data in list html = html.format(*data) except: raise Exception("Problem parsing data to template") return html