Elektra  0.8.23
How-To: Python kdb

Introduction

When programming in Python it is possible to access the kdb database, changing values of existing keys, adding and deleting keys and a few other things.

First Steps

In order to being able to use kdb, you at first need to import kdb. You need access to a Python object of KDB. This is accomplished by calling kdb.KDB() and saving this to a variable because later on this object will be needed for various operations. The easiest way to do this would be:

1 import kdb
2 
3 with kdb.KDB() as k:
4  print("Hello world! I have a kdb-instance! :D")
5  # do all kinds of operations explained below

Keyset

A keyset is basically a list of the keys that lie within the specified range of the database. When creating an empty keyset this range is obviously zero. It is possible to load the whole database into a keyset but in a lot of cases this is not needed and you can specify which keys exactly you need (which I mean with specified range). At first it is necessary to create a new keyset. When simply calling kdb.KeySet() the keyset is of size 0. There is no restriction to the keyset's size. It is possible to specify a certain (maximum) size for a keyset. To load keys into to keyset from the database you simply call the method get provided by the kdb-object.

1 import kdb
2 
3 with kdb.KDB() as k:
4  # create empty keyset
5  ks = kdb.KeySet()
6  print(len(ks)) # should be 0
7  # load an existing keyset
8  k.get(ks, 'user')

It is also possible to iterate as expected over a keyset and use len, reversed and copying. The elements of a keyset can be accessed by indexes and a keyset can be sliced. Another way of accessing a key is by the key name (`keyset_name['/path/to/keys/key_name']). If a key with the given name does not exist within the keyset, aKeyError` exception is thrown.

An example that shows how to load an existing keyset and then access every key and value of the loaded keyset:

1 import kdb
2 
3 with kdb.KDB() as k:
4  ks = kdb.KeySet()
5  # load an existing keyset
6  k.get(ks, 'user')
7  # if you for some reason want to loop through the keyset last key first
8  # use: for key in reversed(ks):
9  for key in ks:
10  # print for every key in the keyset the key and the value
11  print("key: {} value: {}".format(key, key.value))

Here an example of how you can easily check if a key exists:

1 import kdb
2 
3 with kdb.KDB() as k:
4  namespace = "user"
5  path = '{}/test'.format(namespace)
6 
7  ks = kdb.KeySet()
8  k.get(ks, namespace)
9 
10  try:
11  print("The value of the key {} is {}!".format(ks[path], ks[path]
12  .value))
13  except KeyError:
14  print("The key {} does not exist!".format(path))

Ways of copying a keyset:

1 import copy, kdb
2 
3 with kdb.KDB() as k:
4  ks = kdb.KeySet()
5  k.get(ks, 'spec')
6  # creating a deep copy
7  ks_deepcopy = copy.deepcopy(ks)
8  # creating a shallow copy
9  ks_shallowcopy = copy.copy(ks)

Slicing works just like for normal lists in Python. But be careful: Afterwards the result will be a list - not a keyset.

1 import kdb
2 
3 with kdb.KDB() as k:
4  ks = kdb.KeySet()
5  k.get(ks, 'system')
6 
7  # creating a shallow copy by slicing
8  ks_copy_by_slicing = ks[:]
9 
10  # in the following examples start & end need to be replaced by integers
11  start, end = 1, 3
12  # create keyset with keys from start to end-1
13  a = ks[start:end]
14 
15  # create keyset with keys from start to the end of the original keyset
16  start = len(ks) - 3
17  b = ks[start:]
18 
19  # create keyset with keys from the beginning of the keyset to end
20  c = ks[:end]
21 
22  for keyset in [a, b, c]:
23  for key in keyset:
24  try:
25  print('{}: {}'.format(key, key.value))
26  except UnicodeDecodeError:
27  pass # Ignore keys and values that store non-ASCII characters
28  print('')

If you have changed anything in the keyset and want those changes to be saved to the database, you need to call set which is just like get provided by the kdb-object.

An example of everything up until now could look like this:

1 import kdb
2 
3 with kdb.KDB() as k:
4  ks = kdb.KeySet()
5  k.get(ks, '/path/to/keys')
6 
7  # Any number of operations that manipulate the keyset as explained above
8 
9  # Setting and by doing so saving the new keyset
10  k.set(ks, '/path/to/keys')
11  # by changing the path here it is for instance possible to set the keyset
12  # of one user identical to another users

If you have a key a very simple way to get its name and value:

1 import kdb
2 
3 with kdb.KDB() as k:
4  ks = kdb.KeySet()
5  k.get(ks, 'user')
6  for key in ks:
7  print("key name: {}".format(key.name))
8  print("{0}{1}\n{0}{2}\n".format("key value: ", key.value,
9  ks.lookup(key).string))

It is possible to create new keys:

1 import kdb
2 
3 with kdb.KDB() as k:
4  # the first argument is the path to the key,
5  # the third argument is the key's value
6  new_key = kdb.Key('/user/sw/pk/key_name', kdb.KEY_VALUE, 'key_value')
7  print("{}: {}".format(new_key, new_key.value))

Keys can be added to a keyset using append. If the key already exists, the value will be updated. Calling `keyset_name['/path/to/key'] = 'new_value` does not work for updating keys already in a keyset.

1 from kdb import KDB, KEY_VALUE, Key, KeySet
2 
3 
4 class KeySet(KeySet):
5  def __repr__(self):
6  """Return a textual representation of this keyset."""
7  return '\n'.join(
8  ['{}: {}'.format(key.name, key.value) for key in self])
9 
10 
11 def key(name, value):
12  """Create a new key with the given name and value."""
13  return Key(name, KEY_VALUE, value)
14 
15 
16 def describe(keyset, title, newline=True):
17  return '{}\n{}\n{}{}'.format(title, '=' * len(title), keyset,
18  '\n' if newline else '')
19 
20 
21 with KDB() as data:
22  keyset = KeySet()
23  data.get(keyset, 'user')
24  print(describe(keyset, "Initial Keyset"))
25 
26  new_key = key('user/sw/pk/key_name', 'key_value')
27  # adding new_key to the existing key-set,
28  # ks['/user/sw/pk/key_name'].value == 'key_value'
29  keyset.append(new_key)
30  print(describe(keyset, "Add New Key"))
31 
32  newer_key = key('user/sw/pk/key_name', 'other_key_value')
33  # adding newer_key to the existing key-set, by doing so replacing new_key,
34  # ks['/user/sw/pk/key_name'].value == 'other_key_value'
35  keyset.append(newer_key)
36  print(describe(keyset, "Replace Key", newline=False))