utils.py 1.81 KB
Newer Older
Sorrel Harriet's avatar
Sorrel Harriet committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/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