Elektra
0.9.3
|
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.
Either build the package or install from a repository.
The python bindings package is only available in the testing repository (as of 2019-04-29).
Under regular alpine, you have to install python3 from the edge repository. If you do not want to add the edge repositories permanently like above, you can do
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:
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.
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, a
KeyError` exception is thrown.
An example that shows how to load an existing keyset and then access every key and value of the loaded keyset:
Here an example of how you can easily check if a key exists:
Ways of copying a keyset:
Slicing works just like for normal lists in Python. But be careful: Afterwards the result will be a list - not a keyset.
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:
If you have a key a very simple way to get its name and value:
It is possible to create new keys:
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.