Coverage for /builds/kinetik161/ase/ase/db/project.py: 97.87%
47 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-12-10 11:04 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-12-10 11:04 +0000
1from pathlib import Path
3from ase.db.core import KeyDescription
4from ase.db.row import row2dct
5from ase.formula import Formula
8class DatabaseProject:
9 """Settings for web view of a database.
11 For historical reasons called a "Project".
12 """
13 _ase_templates = Path('ase/db/templates')
15 def __init__(self, name, title, *,
16 key_descriptions,
17 database,
18 default_columns):
19 self.name = name
20 self.title = title
21 self.uid_key = 'id'
23 # The templates loop over "key descriptions" when they want to
24 # loop over keys.
25 #
26 # Therefore, any key without description will not be rendered.
27 # Therefore, we need to make dummy key descriptions of everything
28 # in the database, ensuring that all keys are visible.
30 all_keys = database.get_all_key_names()
32 key_descriptions = {
33 **{key: KeyDescription(key) for key in all_keys},
34 **key_descriptions}
36 for key, value in key_descriptions.items():
37 assert isinstance(key, str), type(key)
38 assert isinstance(value, KeyDescription), type(value)
40 self.key_descriptions = key_descriptions
41 self.database = database
42 self.default_columns = default_columns
44 def get_search_template(self):
45 return self._ase_templates / 'search.html'
47 def get_row_template(self):
48 return self._ase_templates / 'row.html'
50 def get_table_template(self):
51 return self._ase_templates / 'table.html'
53 def handle_query(self, args) -> str:
54 """Convert request args to ase.db query string."""
55 return args['query']
57 def row_to_dict(self, row):
58 """Convert row to dict for use in html template."""
59 dct = row2dct(row, self.key_descriptions)
60 dct['formula'] = Formula(row.formula).convert('abc').format('html')
61 return dct
63 def uid_to_row(self, uid):
64 return self.database.get(f'{self.uid_key}={uid}')
66 @classmethod
67 def dummyproject(cls, **kwargs):
68 class DummyDatabase:
69 def select(self, *args, **kwargs):
70 return iter([])
72 def get_all_key_names(self):
73 return set()
75 _kwargs = dict(
76 name='test',
77 title='test',
78 key_descriptions={},
79 database=DummyDatabase(), # XXX
80 default_columns=[])
81 _kwargs.update(kwargs)
82 return cls(**_kwargs)
84 # If we make this a classmethod, and try to instantiate the class,
85 # it would fail on subclasses. So we use staticmethod
86 @staticmethod
87 def load_db_as_ase_project(name, database):
88 from ase.db.core import get_key_descriptions
89 from ase.db.table import all_columns
91 return DatabaseProject(
92 name=name,
93 title=database.metadata.get('title', ''),
94 key_descriptions=get_key_descriptions(),
95 database=database,
96 default_columns=all_columns)