Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1#!/usr/local/bin/python 

2# encoding: utf-8 

3""" 

4*Given a yaml settings file containing database connection details, setup and return the db connector* 

5 

6:Author: 

7 David Young 

8""" 

9from builtins import str 

10import sys 

11import os 

12import yaml 

13try: 

14 yaml.warnings({'YAMLLoadWarning': False}) 

15except: 

16 pass 

17os.environ['TERM'] = 'vt100' 

18from fundamentals import tools 

19 

20 

21def setup_database_connection( 

22 pathToYamlFile): 

23 """*Start a database connection using settings in yaml file*  

24 

25 Given the location of a YAML dictionary containing database credientials, this function will setup and return the connection* 

26 

27 **Key Arguments** 

28 

29 - ``pathToYamlFile`` -- path to the YAML dictionary. 

30 

31 

32 **Return** 

33 

34 - ``dbConn`` -- connection to the MySQL database. 

35 

36 

37 **Usage** 

38 

39 The settings file should be in this form, with all keyword values set: 

40 

41 ```yaml 

42 db: unit_tests 

43 host: localhost 

44 user: utuser 

45 password: utpass 

46 ``` 

47 

48 And here's how to generate the connection object: 

49 

50 ```python 

51 from fundamentals.mysql import setup_database_connection 

52 dbConn = setup_database_connection( 

53 pathToYamlFile=pathToMyYamlFile 

54 ) 

55 ``` 

56 

57 """ 

58 import sys 

59 import logging 

60 import coloredlogs 

61 import pymysql as ms 

62 

63 # IMPORT THE YAML CONNECTION DICTIONARY 

64 try: 

65 logging.info( 

66 'importing the yaml database connection dictionary from ' + pathToYamlFile) 

67 stream = open(pathToYamlFile, 'r') 

68 connDict = yaml.load(stream) 

69 except: 

70 logging.critical( 

71 'could not load the connect dictionary from ' + pathToYamlFile) 

72 sys.exit(1) 

73 # ESTABLISH A DB CONNECTION 

74 try: 

75 logging.info('connecting to the ' + connDict[ 

76 'db'] + ' database on ' + connDict['host']) 

77 dbConn = ms.connect( 

78 host=connDict['host'], 

79 user=connDict['user'], 

80 passwd=connDict['password'], 

81 db=connDict['db'], 

82 use_unicode=True, 

83 charset='utf8', 

84 local_infile=1, 

85 client_flag=ms.constants.CLIENT.MULTI_STATEMENTS, 

86 connect_timeout=36000 

87 ) 

88 dbConn.autocommit(True) 

89 except Exception as e: 

90 logging.critical('could not connect to the ' + connDict['db'] + ' database on ' + connDict['host'] + ' : ' 

91 + str(e) + '\n') 

92 return dbConn 

93 

94# use the tab-trigger below for new function 

95# xt-def-function