Skip to content

Commit 8f2ffa7

Browse files
modified how configs are handled.
1 parent 14cd0e0 commit 8f2ffa7

5 files changed

Lines changed: 36 additions & 42 deletions

File tree

‎datajoint/__init__.py‎

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -47,23 +47,25 @@ class DataJointError(Exception):
4747
from .settings import Config, LOCALCONFIG, GLOBALCONFIG, logger, log_levels
4848
config = Config()
4949

50-
51-
if os.getenv('DJ_HOST') is not None and os.getenv('DJ_USER') is not None: # pragma: no cover
52-
print("Loading local settings from environment variables")
53-
config['database.host'] = os.getenv('DJ_HOST')
54-
config['database.user'] = os.getenv('DJ_USER')
55-
config['database.password'] = os.getenv('DJ_PASS')
56-
elif os.path.exists(LOCALCONFIG): # pragma: no cover
57-
local_config_file = os.path.expanduser(LOCALCONFIG)
58-
print("Loading local settings from {0:s}".format(local_config_file))
59-
logger.log(logging.INFO, "Loading local settings from {0:s}".format(local_config_file))
60-
config.load(local_config_file)
61-
elif os.path.exists(os.path.expanduser('~/') + GLOBALCONFIG): # pragma: no cover
62-
local_config_file = os.path.expanduser('~/') + GLOBALCONFIG
50+
config_files = (os.path.expanduser(n) for n in (LOCALCONFIG, '~/' + GLOBALCONFIG))
51+
try:
52+
local_config_file = next(n for n in config_files if os.path.exists(n))
53+
except StopIteration:
54+
local_config_file = None
55+
else:
6356
print("Loading local settings from {0:s}".format(local_config_file))
6457
logger.log(logging.INFO, "Loading local settings from {0:s}".format(local_config_file))
6558
config.load(local_config_file)
66-
else:
59+
60+
# override login credentials with environment variables
61+
mapping = {k: v for k, v in zip(
62+
('database.host', 'database.user', 'database.password'),
63+
map(os.getenv, ('DJ_HOST', 'DJ_USER', 'DJ_PASS')))
64+
if v is not None}
65+
config.update(mapping)
66+
67+
# create local config file if neither local nor global file exists
68+
if not mapping and local_config_file is None:
6769
print("""Cannot find configuration settings. Using default configuration. To change that, either
6870
* modify the local copy of %s that datajoint just saved for you
6971
* put a file named %s with the same configuration format in your home

‎datajoint/connection.py‎

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
logger = logging.getLogger(__name__)
1818

1919

20-
def conn(host=None, user=None, passwd=None, init_fun=None, reset=False):
20+
def conn(host=None, user=None, password=None, init_fun=None, reset=False):
2121
"""
2222
Returns a persistent connection object to be shared by multiple modules.
2323
If the connection is not yet established or reset=True, a new connection is set up.
@@ -27,18 +27,20 @@ def conn(host=None, user=None, passwd=None, init_fun=None, reset=False):
2727
2828
:param host: hostname
2929
:param user: mysql user
30-
:param passwd: mysql password
30+
:param password: mysql password
3131
:param init_fun: initialization function
32-
:param reset: whether the connection should be reseted or not
32+
:param reset: whether the connection should be reset or not
3333
"""
3434
if not hasattr(conn, 'connection') or reset:
3535
host = host if host is not None else config['database.host']
3636
user = user if user is not None else config['database.user']
37-
passwd = passwd if passwd is not None else config['database.password']
38-
if passwd is None: # pragma: no cover
39-
passwd = getpass(prompt="Please enter database password: ")
37+
password = password if password is not None else config['database.password']
38+
if user is None: # pragma: no cover
39+
user = input("Please enter DataJoint username: ")
40+
if password is None: # pragma: no cover
41+
password = getpass(prompt="Please enter DataJoint password: ")
4042
init_fun = init_fun if init_fun is not None else config['connection.init_function']
41-
conn.connection = Connection(host, user, passwd, init_fun)
43+
conn.connection = Connection(host, user, password, init_fun)
4244
return conn.connection
4345

4446

@@ -51,17 +53,17 @@ class Connection:
5153
5254
:param host: host name
5355
:param user: user name
54-
:param passwd: password
55-
:param init_fun: initialization function
56+
:param password: password
57+
:param init_fun: connection initialization function (SQL)
5658
"""
5759

58-
def __init__(self, host, user, passwd, init_fun=None):
60+
def __init__(self, host, user, password, init_fun=None):
5961
if ':' in host:
6062
host, port = host.split(':')
6163
port = int(port)
6264
else:
6365
port = config['database.port']
64-
self.conn_info = dict(host=host, port=port, user=user, passwd=passwd)
66+
self.conn_info = dict(host=host, port=port, user=user, passwd=password)
6567
self.init_fun = init_fun
6668
print("Connecting {user}@{host}:{port}".format(**self.conn_info))
6769
self._conn = None

‎datajoint/settings.py‎

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,12 @@
3838
default = OrderedDict({
3939
'database.host': 'localhost',
4040
'database.password': None,
41-
'database.user': 'datajoint',
41+
'database.user': None,
4242
'database.port': 3306,
43-
'database.reconnect': False,
44-
#
4543
'connection.init_function': None,
46-
#
44+
'database.reconnect': False,
4745
'loglevel': 'INFO',
48-
#
4946
'safemode': True,
50-
#
5147
'display.limit': 7,
5248
'display.width': 14
5349
})
@@ -97,7 +93,6 @@ def __iter__(self):
9793
def __len__(self):
9894
return len(self.instance._conf)
9995

100-
10196
@contextmanager
10297
def __call__(self, **kwargs):
10398
"""
@@ -106,17 +101,15 @@ def __call__(self, **kwargs):
106101
double underscore '__'. The context manager yields the changed config object.
107102
108103
Example:
109-
110104
>>> import datajoint as dj
111-
>>> with dj.config(safe__mode=False) as cfg:
105+
>>> with dj.config(safemode=False, database__host="localhost") as cfg:
112106
>>> # do dangerous stuff here
113-
114107
"""
115108

116109
try:
117110
backup = self.instance
118111
self.instance = Config.__Config(self.instance._conf)
119-
new = {k.replace('__','.'):v for k,v in kwargs.items()}
112+
new = {k.replace('__', '.'): v for k, v in kwargs.items()}
120113
self.instance._conf.update(new)
121114
yield self
122115
except:
@@ -125,15 +118,13 @@ def __call__(self, **kwargs):
125118
else:
126119
self.instance = backup
127120

128-
129121
class __Config:
130122
"""
131123
Stores datajoint settings. Behaves like a dictionary, but applies validator functions
132124
when certain keys are set.
133125
134126
The default parameters are stored in datajoint.settings.default . If a local config file
135127
exists, the settings specified in this file override the default settings.
136-
137128
"""
138129

139130
def __init__(self, *args, **kwargs):
@@ -165,8 +156,7 @@ def save(self, filename=None):
165156
def load(self, filename):
166157
"""
167158
Updates the setting from config file in JSON format.
168-
169-
:param filename=None: filename of the local JSON settings file. If None, the local config file is used.
159+
:param filename: filename of the local JSON settings file. If None, the local config file is used.
170160
"""
171161
if filename is None:
172162
filename = LOCALCONFIG

‎requirements.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,4 @@ scipy
33
pymysql
44
pyparsing
55
networkx
6-
matplotlib
6+
matplotlib

‎tests/__init__.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
CONN_INFO = dict(
2323
host=environ.get('DJ_TEST_HOST', 'localhost'),
2424
user=environ.get('DJ_TEST_USER', 'datajoint'),
25-
passwd=environ.get('DJ_TEST_PASSWORD', 'datajoint'))
25+
password=environ.get('DJ_TEST_PASSWORD', 'datajoint'))
2626

2727
# Prefix for all databases used during testing
2828
PREFIX = environ.get('DJ_TEST_DB_PREFIX', 'djtest')

0 commit comments

Comments
 (0)