Skip to content

Commit

Permalink
Fix #6 - Provide ability to connect to db on non-default port (#7)
Browse files Browse the repository at this point in the history
* Fix #6 - Provide ability to connect to db on non-default port
  • Loading branch information
Devashish Chandra authored and mastizada committed Jun 3, 2016
1 parent aefa823 commit 21b3f0f
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
3 changes: 2 additions & 1 deletion credentials.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
"host": "",
"user": "",
"password": "",
"database": ""
"database": "",
"port": 3306
}
2 changes: 1 addition & 1 deletion dbConnect/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
__license__ = "MPL 2.0"
__doc__ = """MySQL for Humans"""

from .dbconnect import DBConnect
from .dbConnect import DBConnect
13 changes: 8 additions & 5 deletions dbConnect/dbConnect.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ def _check_settings(self):
Check configuration file
:return: True if all settings are correct
"""
keys = ['host', 'user', 'password', 'database']
keys = ['host', 'user', 'password', 'database', 'port']
if not all(key in self.settings.keys() for key in keys):
raise ValueError('Please check credentials file for correct keys: host, user, password, database')
raise ValueError('Please check credentials file for correct keys: host, user, password, database, port')

def connect(self):
"""
Expand All @@ -33,7 +33,8 @@ def connect(self):
password=self.settings['password'],
host=self.settings['host'],
database=self.settings['database'],
charset='utf8')
charset='utf8',
port=self.settings['port'])
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
raise ValueError("Wrong credentials, ACCESS DENIED")
Expand All @@ -43,14 +44,16 @@ def connect(self):
raise ValueError(err)
self.cursor = self.connection.cursor()

def __init__(self, credentials_file='credentials.json', host=None, user=None, password=None, database=None):
def __init__(self, credentials_file='credentials.json', host=None, user=None, password=None, database=None, port=3306):
"""
Initialise object with credentials file provided
"""
if host and user and password and database:
self.settings = {"host": host, "user": user, "password": password, "database": database}
self.settings = {"host": host, "user": user, "password": password, "database": database, "port": port}
else:
self.settings = json.load(open(credentials_file, 'r'))
if 'port' not in self.settings:
self.settings['port'] = port
self._check_settings(self)
self.connection = None
self.cursor = None
Expand Down

0 comments on commit 21b3f0f

Please sign in to comment.