viktor.core
UserException
- exception viktor.core.UserException(*args)¶
Bases:
Exception
Deprecated, please use
viktor.errors.UserError
instead.
InitialEntity
- class viktor.core.InitialEntity(entity_type_name, name, *, params=None, children=None, show_on_dashboard=None)¶
-
Construct an initial entity in the app.__init__py file.
from .settings_database.controller import Controller as SettingsDatabaseController from .project_folder.controller import Controller as ProjectFolderController from .project.controller import Controller as ProjectController from viktor import InitialEntity initial_entities = [ InitialEntity('SettingsDatabase', name='Settings', params=...), InitialEntity('ProjectFolder', name='Projects', children=[ InitialEntity('Project', 'Project X), InitialEntity('Project', 'Project Y), ]), ]
- Parameters
entity_type_name (
str
) – Type of the initial entity.name (
str
) – Name of the initial entity.params (
Union
[dict
,str
,None
]) – Optional params in dictionary format or path to a .json, relative to the app.__init__.py. Note that path traversal (beyond the root directory) is not permitted (e.g. “../../entity.json”).children (
Optional
[List
[InitialEntity
]]) – Optional child entities.show_on_dashboard (
Optional
[bool
]) – Show/hide the entity on the dashboard. Only top-level entities can be shown (default: True)New in v13.7.0
ParamsFromFile
- class viktor.core.ParamsFromFile(*, max_size=None, file_types=None)¶
-
Decorator that can be used on a pre-process method during a file upload, to produce the parameter set that is stored in the database.
Warning
Prevent storing the complete file content on the properties if the file is large, as this may cause speed and/or stability issues. The file content can be retrieved at all times using the API whenever necessary.
Example with nothing to store:
class Controller(ViktorController): ... @ParamsFromFile(...) def process_file(self, file: File, **kwargs): # viktor.core.File return {}
Example with parameters to store:
class Controller(ViktorController): ... @ParamsFromFile(...) def process_file(self, file: File, **kwargs): # viktor.core.File # app specific parsing logic file_content = file.getvalue() # or use reading in chunks, for large files number_of_entries = ... project_name = ... # linking the parsed output to the parametrization fields (names in database) return { 'tab': { 'section': { 'number_of_entries': number_of_entries, 'project_name': project_name } } }
Warning
Loading the content of a large file in memory (file.getvalue()) may cause the app to crash (out-of-memory). Read the file content in chunks to avoid such memory issues (see
File
).Note
viktor.testing.mock_ParamsFromFile()
can be used to test methods decorated with ParamsFromFile.- Parameters
max_size (
Optional
[int
]) – optional restriction on file size in bytes (e.g. 10_000_000 = 10 MB).file_types (
Optional
[Sequence
[str
]]) – optional restriction on file type(s) (e.g. [‘.png’, ‘.jpg’, ‘.jpeg’]). Note that the extensions are filtered regardless of capitalization.
ViktorController
- class viktor.core.ViktorController(**kwargs)¶
-
The main function of the ViktorController is to “control” the information flow between the frontend (what is inputted by a user) and the application code (what is returned as a result of the user input).
- label: str¶
Entity-type label.
- children: Optional[List[str]] = None¶
Optional list of child entity-types.
- show_children_as: Optional[str] = None¶
When children are defined, specify how they are shown in the interface (‘Table’ | ‘Cards’).
- summary: Optional[Summary] = None¶
viktor.views.Summary
of the entity-type.
- parametrization: Optional[Parametrization] = None¶
viktor.parametrization.Parametrization
that describes the entity-type.
File
- class viktor.core.File(*, data=None, path=None, url=None, **kwargs)¶
-
Creates a File object. Only 1 of data, path or url should be set, or File() for writable file. Or use the corresponding class-methods.
A File object can have one of the following 4 types:
SourceType.DATA: File object with in-memory data as its source
Created with File.from_data(…)
writable: False
SourceType.PATH: File object with an existing file (path) as its source
Created with File.from_path(…)
writable: False
SourceType.URL: File object with a URL as its source
Created with File.from_url(…)
writable: False
SourceType.WRITABLE: File object with a (temporary) writable file on disk as its source
Created with File()
writable: True (writing always takes place at end of file)
Note: Reading from a File with SourceType.URL downloads (part of the) URL content to a (temporary) file on disk, so that re-reading (previously read) content within the same open-context does not require downloading twice. Opening the File object a second time DOES involve downloading the content anew. If such a File needs to be opened multiple times, consider copying the File locally (
copy()
), so that downloading takes place only once.Example usage:
data_file = File.from_data("my content") path_file = File.from_path(Path(__file__).parent / "my_file.txt") url_file = File.from_url("https://...") writable_file = File() data_content = data_file.getvalue_binary() # bytes (b"my content") path_content = path_file.getvalue() # str with url_file.open() as r: # open in text-mode, so read -> str first_character = r.read(1) # downloads only partially all_other_characters = r.read() # downloads the rest with writable_file.open_binary() as w: # open as binary-mode, so read/write -> bytes w.write(b"my content") writable_content = writable_file.getvalue() # "my content"
- Parameters
data (
Union
[str
,bytes
,None
]) – in-memory data source (alsofrom_data()
)path (
Union
[str
,bytes
,PathLike
,None
]) – existing file path source (alsofrom_path()
)url (
Optional
[str
]) – URL source (alsofrom_url()
)
- class SourceType(value)¶
Bases:
Enum
An enumeration.
- DATA: SourceType = 1¶
- PATH: SourceType = 2¶
- URL: SourceType = 3¶
- WRITABLE: SourceType = 4¶
- classmethod from_data(data)¶
Create a File object with in-memory data as its source.
- Return type
- classmethod from_path(path)¶
Create a File object with an existing file (path) as its source.
- Return type
- classmethod from_url(url, *, headers=None)¶
Create a File object with a URL as its source.
- Return type
- property source: Optional[str]¶
Source of the File object:
SourceType.DATA -> None
SourceType.PATH -> path of (readable) file on disk
SourceType.URL -> url
SourceType.WRITABLE -> path of (writable) file on disk
- Return type
Optional
[str
]
- property source_type: SourceType¶
Source type of the file.
- Return type
- property writable: bool¶
Whether the File is writable or not (only True for SourceType.WRITABLE).
- Return type
bool
- open(encoding=None)¶
Open the file in text-mode.
- Parameters
encoding (
Optional
[str
]) – encoding used for reading the bytes -> str (default: default local encoding)- Return type
TextIO
- Returns
opened text file
- open_binary()¶
Open the file in binary-mode.
- Return type
BinaryIO
- Returns
opened binary file
- getvalue(encoding=None)¶
Read the content (text) of the file in memory. For large files, open the file and read in chunks, to prevent the app from running out of memory.
- Return type
str
- getvalue_binary()¶
Read the content (binary) of the file in memory. For large files, open the file and read in chunks, to prevent the app from running out of memory.
- Return type
bytes
- copy(writable=False)¶
Make a local copy of the file to disk.
Example usages:
URL-file that needs to be opened multiple times:
# copying to path-file prevents re-downloading if opening more than once. path_file = url_file.copy() # download the complete content locally with path_file.open() as r: # no downloading ... with path_file.open() as r: # no downloading ...
Make writable file from read-only file:
writable_file = read_only_file.copy(writable=True) with writable_file.open() as w: w.write("my content")
- Parameters
writable (
bool
) – True to return writable file, False for read-only (default: False).- Return type
- Returns
File object (SourceType.WRITABLE if writable = True, else SourceType.PATH).
Color
- class viktor.core.Color(r: int, g: int, b: int)¶
Bases:
Color
Create an immutable instance of Color
- Parameters
r – red-value (0-255)
g – green-value (0-255)
b – blue-value (0-255)
- classmethod from_deltares(value)¶
Color defined by Deltares-type integer.
- Parameters
value (
int
) – Integer representation of the color as used in the Deltares software series.- Return type
- property rgb: Tuple[int, int, int]¶
- Return type
Tuple
[int
,int
,int
]
- property hex: str¶
Hexadecimal representation of the color.
- Return type
str
- property deltares: int¶
- Return type
int
- static rgb_to_hex(r, g, b, include_hashtag=True)¶
Conversion from red-green-blue to hexadecimal value
- Return type
str
- static hex_to_rgb(hex_value)¶
Conversion from hexadecimal to red-green-blue value
- Return type
Tuple
[int
,int
,int
]
- static rgb_to_deltares(r, g, b)¶
Conversion from Deltares-type color value to red-green-blue value.
:return Integer representation of the color as used in the Deltares software series.
- Return type
int
- static deltares_to_rgb(value)¶
Conversion from red-green-blue to Deltares-type color value.
- Parameters
value (
int
) – Integer representation of the color as used in the Deltares software series.- Return type
Tuple
[int
,int
,int
]
progress_message
- viktor.core.progress_message(message, percentage=None)¶
Send a user facing progress message informing the progress of an evaluation. Messages are truncated to 500 characters
- Parameters
message (
str
) – Message shown to the userpercentage (
Optional
[float
]) – Value between 0 and 100 quantifying the progress
- Return type
None
make_data_json_serializable
- viktor.core.make_data_json_serializable(input_data)¶
The python built-in json dump does not support all the desired types. This function converts those, thereby enabling broader json conversion.
numpy number types -> equivalent python builtin
datetime.datetime and datetime.date -> isoformat str
tuple -> list (otherwise sub elements cannot be converted due to tuple immutability)
- Return type
Any
Storage
- class viktor.core.Storage¶
-
Starting point to communicate with the storage to, for example, set or retrieve analysis results.
The following actions are supported:
storage = Storage() # Setting data on a key storage.set('data_key_1', data=File.from_data('abc'), scope='entity') storage.set('data_key_2', data=File.from_data('def'), scope='entity') # Retrieve the data by key storage.get('data_key_1', scope='entity') # List available data keys (by prefix) storage.list(scope='entity') # lists all files in current entity scope storage.list(prefix='data_key_', scope='entity') # lists 'data_key_1', 'data_key_2', ... etc. # Delete data by key storage.delete('data_key_1', scope='entity')
For each of these methods, a scope can be defined to point to a specific section in the storage. These scopes ensure efficient arrangement and handling of data. The following scopes can be used:
entity : when data needs to be accessed within a specific entity
workspace : when data needs to be accessed workspace-wide
- set(key, data, *, scope, entity=None)¶
Set data on a key for the specified scope.
- Parameters
- Return type
None
- get(key, *, scope, entity=None)¶
Retrieve data from a key for the specified scope.
- Parameters
key (
str
) – Unique key from which the data should be retrieved.scope (
str
) – Applicable scope, ‘entity’ | ‘workspace’.entity (
Optional
[Entity
]) – Applicable entity, used in combination with scope==’entity’ (default: current entity).
- Raises
FileNotFoundError – When trying to retrieve a file that does not exist in the defined storage scope.
- Return type
- delete(key, *, scope, entity=None)¶
Delete a key-value pair for the specified scope.
- Parameters
key (
str
) – Unique key from which the key-value pair should be deleted.scope (
str
) – Applicable scope, ‘entity’ | ‘workspace’.entity (
Optional
[Entity
]) – Applicable entity, used in combination with scope==’entity’ (default: current entity).
- Raises
FileNotFoundError – When trying to delete a file that does not exist in the defined storage scope.
- Return type
None
- list(*, prefix=None, scope, entity=None)¶
List all available key-value pairs for the specified scope.
- Parameters
prefix (
Optional
[str
]) – List all data of which the keys start with the provided prefix. Using a prefix potentially results in much higher performance due to a more efficient lookup in case of many stored files.scope (
str
) – Applicable scope, ‘entity’ | ‘workspace’.entity (
Optional
[Entity
]) – Applicable entity, used in combination with scope==’entity’ (default: current entity).
- Return type
Dict
[str
,File
]