158
158
class Config(dict):
159
"""A Juju charm config dictionary that can write itself to
160
disk (as json) and track which values have changed since
161
the previous hook invocation.
163
Do not instantiate this object directly - instead call
159
"""A dictionary representation of the charm's config.yaml, with some
162
- See which values in the dictionary have changed since the previous hook.
163
- For values that have changed, see what the previous value was.
164
- Store arbitrary data for use in a later hook.
166
NOTE: Do not instantiate this object directly - instead call
167
``hookenv.config()``, which will return an instance of :class:`Config`.
188
191
>>> # keys/values that we add are preserved across hooks
189
192
>>> config['mykey']
191
>>> # don't forget to save at the end of hook!
195
196
CONFIG_FILE_NAME = '.juju-persistent-config'
197
198
def __init__(self, *args, **kw):
198
199
super(Config, self).__init__(*args, **kw)
200
self.implicit_save = True
199
201
self._prev_dict = None
200
202
self.path = os.path.join(charm_dir(), Config.CONFIG_FILE_NAME)
201
203
if os.path.exists(self.path):
202
204
self.load_previous()
206
def __getitem__(self, key):
207
"""For regular dict lookups, check the current juju config first,
208
then the previous (saved) copy. This ensures that user-saved values
209
will be returned by a dict lookup.
213
return dict.__getitem__(self, key)
215
return (self._prev_dict or {})[key]
204
217
def load_previous(self, path=None):
205
"""Load previous copy of config from disk so that current values
206
can be compared to previous values.
218
"""Load previous copy of config from disk.
220
In normal usage you don't need to call this method directly - it
221
is called automatically at object initialization.
239
254
"""Save this config to disk.
241
Preserves items in _prev_dict that do not exist in self.
256
If the charm is using the :mod:`Services Framework <services.base>`
257
or :meth:'@hook <Hooks.hook>' decorator, this
258
is called automatically at the end of successful hook execution.
259
Otherwise, it should be called directly by user code.
261
To disable automatic saves, set ``implicit_save=False`` on this
244
265
if self._prev_dict:
288
def relation_set(relation_id=None, relation_settings={}, **kwargs):
309
def relation_set(relation_id=None, relation_settings=None, **kwargs):
289
310
"""Set relation information for the current unit"""
311
relation_settings = relation_settings if relation_settings else {}
290
312
relation_cmd_line = ['relation-set']
291
313
if relation_id is not None:
292
314
relation_cmd_line.extend(('-r', relation_id))