18. database — A simple Database class

class database.Database(*, data=None, key='id', record=<class 'database.Record'>)[source]

A class for storing data in a database-like structure.

The Database is a Dict where each key is a unique identifier string and each value is a record. A record is itself a Dict , where each key is a string (the field name) and the value can be anything.

Parameters:
  • default_factory (callable, optional) – If provided, missing keys will be looked up by a call to the default_factory.

  • data (dict | list | str, optional) –

    The Database can be initialized from a dict, a list of records or a file in a proper format.

    If a dict, the Database will be directly initialized from it.

    If a list, each record should have at least a key named ‘name’, holding the string identifying the record. This value should be unique in the list (or records will be overwritten). The ‘name’ value will be use as a key to store the record in the Database.

    If a string, it is the name of a Database file in one of the supported formats, from where it will be read. See read().

    If not provided, an empty database is constructed.

  • key (str, optional) – The field name to be used as a key, if list type data are specified.

Examples

>>> rec1 = {'id': 'john', 'first_name': 'John', 'last_name': 'Doe'}
>>> rec2 = {'id': 'jane', 'first_name': 'Jane', 'last_name': 'Roe'}
>>> db = Database(data=[rec1, rec2])
>>> print(db)
{
    "john": {
        "id": "john",
        "first_name": "John",
        "last_name": "Doe"
    },
    "jane": {
        "id": "jane",
        "first_name": "Jane",
        "last_name": "Roe"
    }
}
>>> db.write('test.json')
>>> db1 = Database(data='test.json')
>>> print(db1)
{
    "john": {
        "id": "john",
        "first_name": "John",
        "last_name": "Doe"
    },
    "jane": {
        "id": "jane",
        "first_name": "Jane",
        "last_name": "Roe"
    }
}
>>> print(type(db1['john']))
<class 'pyformex.database.Record'>
add(data, key=None)[source]

Add a list of records to the database.

Parameters:
  • data (list) – A list of records. Each record should be a dict and have at least a field name equal to the value specified for key.

  • key (str, optional) – The field name in the records to be used as the key to store the records in the Database.

write(filename)[source]

Export the Database to a file.

The file is written in .json format and contains a dict with two keys: ‘key’ and ‘records’. The key is a

read(filename)[source]

Import all records from a Database file.

Parameters:

filename (path_like) – The file holding the Database. The file should be in .json format as written by write().

Examples

>>> db = Database()
>>> db.read(pf.cfg['prop/matdb'])
>>> print(db)
{
    "steel": {
        "name": "steel",
        "young_modulus": 207000.0,
        "poisson_ratio": 0.3,
        "density": 7.85e-09
    },
...