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 

9:Date Created: 

10 June 21, 2016 

11""" 

12################# GLOBAL IMPORTS #################### 

13from builtins import str 

14import sys 

15import os 

16import yaml 

17try: 

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

19except: 

20 pass 

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

22from fundamentals import tools 

23 

24 

25def setup_database_connection( 

26 pathToYamlFile): 

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

28 

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

30 

31 **Key Arguments:** 

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

33 

34 **Return:** 

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

36 

37 **Usage:** 

38 

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

40 

41 .. code-block:: yaml 

42 

43 db: unit_tests 

44 host: localhost 

45 user: utuser 

46 password: utpass 

47 

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

49 

50 .. code-block:: python  

51 

52 from fundamentals.mysql import setup_database_connection 

53 dbConn = setup_database_connection( 

54 pathToYamlFile=pathToMyYamlFile 

55 ) 

56 """ 

57 import sys 

58 import logging 

59 import pymysql as ms 

60 

61 # IMPORT THE YAML CONNECTION DICTIONARY 

62 try: 

63 logging.info( 

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

65 stream = open(pathToYamlFile, 'r') 

66 connDict = yaml.load(stream) 

67 except: 

68 logging.critical( 

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

70 sys.exit(1) 

71 # ESTABLISH A DB CONNECTION 

72 try: 

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

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

75 dbConn = ms.connect( 

76 host=connDict['host'], 

77 user=connDict['user'], 

78 passwd=connDict['password'], 

79 db=connDict['db'], 

80 use_unicode=True, 

81 charset='utf8', 

82 local_infile=1, 

83 client_flag=ms.constants.CLIENT.MULTI_STATEMENTS, 

84 connect_timeout=36000 

85 ) 

86 dbConn.autocommit(True) 

87 except Exception as e: 

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

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

90 return dbConn 

91 

92 

93# use the tab-trigger below for new function 

94# xt-def-function