Utils#
Utility functions for the ngapp module
- class ngapp.utils.BackendSettingsFile(name: str)#
Bases:
SettingsFileSettingsFile kept as user data of the backend (one record per name): the settings of an app in the browser, whose file system is not persistent
- Parameters:
name (str)
- class ngapp.utils.BackendUserSettings(app_id: str)#
Bases:
BackendSettingsFileUserSettings of an app in the browser with a backend
- Parameters:
app_id (str)
- class ngapp.utils.BaseFrontend(link: LinkBase)#
Bases:
objectBase class for the frontend
- Parameters:
link (LinkBase)
- flush(wait=True)#
Send buffered component updates
- get_query_parameter(name: str)#
Get a query parameter from the URL
- Parameters:
name (str)
- class ngapp.utils.ComputeEnvironment(
- *,
- name: str = 'default',
- cpus: int = 1,
- memory: int = 1024,
- gpu_memory: int = 0,
- scratch: int = 0,
- env_type: Literal['venv', 'docker', 'local'] = 'venv',
- dockerfile: str = '\nFROM ubuntu:25.10\nENV DEBIAN_FRONTEND=noninteractive\nRUN apt update && apt-get -y upgrade\nRUN apt install -y python3 python3-pip python3-venv\nRUN python3 -m venv /opt/venv\nENV PATH="/opt/venv/bin:$PATH"\n',
- pip_dependencies: list[str] = [],
- python: Annotated[str, _PydanticGeneralMetadata(pattern='^(\\d+\\.\\d+)?$')] = '',
- api: bool = False,
- api_workers: int = 1,
- api_timeout: int = 30,
Bases:
BaseModelDefines the resources of compute environments on the backend; memory values are in MB, strings like “512M” or “8G” are accepted
- Parameters:
name (str)
cpus (int)
memory (int)
gpu_memory (int)
scratch (int)
env_type (Literal['venv', 'docker', 'local'])
dockerfile (str)
pip_dependencies (list[str])
python (str)
api (bool)
api_workers (int)
api_timeout (int)
- class ngapp.utils.Environment(type: EnvironmentType, have_backend: bool, link=None)#
Bases:
objectEnvironment class to store the current environment
Following situations are possible:
- 1.) Pyodide environment
type = EnvironmentType.PYODIDE have_backend = True | False
This python instance is running in the browser in a web worker and communicates with the main thread via web worker postMessage interface.
- The backend might be:
No backend (frontend-only apps)
A full backend with http + websocket interface
- 2.) Local App environment
type = EnvironmentType.LOCAL_APP
This python instance is running on a local machine and communicates with the frontend (also running locally) via websockets.
- 3.) Compute environment
type = EnvironmentType.COMPUTE
This is a compute node running a compute function. It communicates with the full backend via http api interface.
- 4.) Standalone environment
type = EnvironmentType.STANDALONE
- Parameters:
type (EnvironmentType)
have_backend (bool)
- begin_save_file_local(filename: str, options: dict | None = None)#
Open the save file picker and return a writer callback.
- Parameters:
filename (str)
options (dict | None)
- load_file_local(options: dict | None = None)#
(name, bytes) of a file chosen in the browser, None if cancelled
- Parameters:
options (dict | None)
- class ngapp.utils.EnvironmentType(*values)#
Bases:
str,EnumEnvironment type PYODIDE: Environment is a frontend (running with pyodide in the browser) COMPUTE: We are running a compute function on a separate compute node LOCAL_APP: Backend serves one app locally STANDALONE: Standalone mode with no frontend, used for testing
- class ngapp.utils.JSFile(name: str, lastModified: int, type: str, size: int, data: bytes)#
Bases:
object- Parameters:
name (str)
lastModified (int)
type (str)
size (int)
data (bytes)
- class ngapp.utils.LocalJob(func, instance, args, kwargs, job_component=None)#
Bases:
objectHandle for a compute function running on the local machine.
Mirrors the interface of
Job(the handle returned in the browser) so app code can treat both the same. InLOCAL_APPthe function runs in a background thread, inSTANDALONEit runs synchronously.- abort()#
Request cancellation. The compute function must poll is_cancelled.
- class ngapp.utils.SettingsFile(path: Path)#
Bases:
objectJSON-backed key/value store for small settings files.
This is a generic helper that loads and saves a JSON file on demand and exposes
get,setandupdateutilities. It is used byUserSettingsfor both the mainconfig.jsonand any additional JSON settings files in the app’s settings directory.- Parameters:
path (Path)
- get(key: str, default=None)#
Get a setting by key, returning default if missing.
- Parameters:
key (str)
- ref(key: str, default=None, converter=None)#
Observable of a setting: writing it stores the setting, and
set()updates it, so bound inputs and views follow.>>> QToggle(ui_model_value=app.usersettings.ref("axes", True))
- Parameters:
key (str)
- set(key: str, value, *, autosave: bool = True) None#
Set a setting value and persist it (by default).
- Parameters:
key (str)
autosave (bool)
- Return type:
None
- update(key: str)#
Return a handler suitable for on_update_model_value.
Example:
nthreads = QInput( ui_label="Number of Threads", ui_model_value=app.usersettings.get("nthreads", default=None), ) nthreads.on_update_model_value( app.usersettings.update("nthreads") )
- Parameters:
key (str)
- class ngapp.utils.UserSettings(
- app_id: str,
- path: Path | None = None,
- app_name: str = 'ngapp',
Bases:
SettingsFileSimple persistent storage for user-wide, per-app settings.
Each app gets its own subfolder within the ngapp user config directory, and the main settings are stored in
config.jsoninside that folder.Additional JSON settings files for the same app can be created via
json_file().- Parameters:
app_id (str)
path (Path | None)
app_name (str)
- property directory: Path#
Directory that contains this app’s JSON settings files.
- json_file(name: str) SettingsFile#
Return a SettingsFile wrapper for an additional JSON file.
The file is created on first save.
.jsonis appended to name if it does not already end with it.- Parameters:
name (str)
- Return type:
- ngapp.utils.call_js(func, *args, **kwargs)#
Call a javascript function in the frontend
- ngapp.utils.compute_node(
- _func=None,
- *,
- compute_env: str | ComputeEnvironment = 'default',
- job_timeout: int | None = None,
- background: bool = False,
Compatibility alias of ngapp.jobs.compute
- Parameters:
compute_env (str | ComputeEnvironment)
job_timeout (int | None)
background (bool)
- ngapp.utils.copy_file(app)#
Create a new file and copy the data
- ngapp.utils.default_usersettings_dir(app_id: str, app_name: str = 'ngapp') Path#
Return the default directory for storing user-wide settings of an app.
The directory is placed inside the ngapp user config directory and named after the given app_id (sanitized to be filesystem-safe).
- Parameters:
app_id (str)
app_name (str)
- Return type:
Path
- ngapp.utils.default_usersettings_path(app_id: str, app_name: str = 'ngapp') Path#
Return the default config.json path for an app’s user settings.
- Parameters:
app_id (str)
app_name (str)
- Return type:
Path
- ngapp.utils.error(*args) None#
Log an message to the console
- Return type:
None
- ngapp.utils.flush_updates()#
Run pending reactions and send the component updates collected so far to the browser now (they are sent when the running event handler returns otherwise). Use it before raw JavaScript calls that rely on the updated page and for progress inside a long handler.
- ngapp.utils.get_current_job() LocalJob | None#
Get the handle of the compute function running in this thread, if any.
Only local jobs have a handle; on a compute node the job runs in its own process and is stopped by killing it.
- Return type:
LocalJob | None
- ngapp.utils.get_job_component()#
Get the current job component of the running job
- ngapp.utils.is_cancelled() bool#
Whether the running compute function was asked to stop.
Long running compute functions should poll this and return early (saving what they have) when it turns true. On a compute node the process is killed instead, so this always returns False there.
- Return type:
bool
- ngapp.utils.is_production() bool#
Check if the code is executed in pyodide
- Return type:
bool
- ngapp.utils.is_pyodide() bool#
Check if the code is executed in pyodide (cached, a failed import is not)
- Return type:
bool
- ngapp.utils.load_file_backend(file_id: str)#
Load a file from backend with given file id
- Parameters:
file_id (str)
- ngapp.utils.log(*args) None#
Log a message to the console
- Return type:
None
- ngapp.utils.new_file(app, data=None)#
Create a new file
- ngapp.utils.parse_memory(value) int#
Memory-like quantity in MB: 512 (MB), “512M”, “8G”, “1T”, “16GiB”
- Return type:
int
- ngapp.utils.print_exception(
- ex,
- file=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>,
Prints the exception and the traceback in red
- ngapp.utils.read_file(filename: str | Path) str#
Read a file from the filesystem
- Parameters:
filename (str | Path)
- Return type:
str
- ngapp.utils.read_file_binary(filename: str | Path) bytes#
Read a binary file from the filesystem
- Parameters:
filename (str | Path)
- Return type:
bytes
- ngapp.utils.read_json(filename: str | Path) dict#
Read a file from the filesystem
- Parameters:
filename (str | Path)
- Return type:
dict
- ngapp.utils.replace_app(new_app)#
Replace the current app instance with a new one
- ngapp.utils.set_directory(path: str)#
Context manager to change the current working directory
- Parameters:
path (str)
- ngapp.utils.temp_dir_with_files(
- data: dict[str, bytes | JSFile],
- extract_zip: bool = False,
- return_list=True,
Context manager to handle files stored in a dictionary
- Parameters:
data (dict[str, bytes | JSFile]) – The dictionary containing the file names and data
extract_zip (bool) – Whether to extract zip files
return_list – Whether to return a single file as list, or the file directly
- Yields:
A list containing the file paths objects
- Return type:
list[Path] | Path
- ngapp.utils.time_now() float#
Return the current time as a timestamp
- Return type:
float
- ngapp.utils.warning(*args) None#
Log a warning to the console
- Return type:
None
- ngapp.utils.write_file(
- filename: str | Path,
- data: str | bytes,
- binary: bool = False,
Write a file to the filesystem
- Parameters:
filename (str | Path)
data (str | bytes)
binary (bool)
- Return type:
int
- ngapp.utils.write_json(data: dict, filename: str | Path) None#
Write a file from the filesystem
- Parameters:
data (dict)
filename (str | Path)
- Return type:
None
- ngapp.utils.zip_directory(path: str, ignore: str = '*backend*') bytes#
Zip a directory and return the zip file as a bytes object
- Parameters:
path (str)
ignore (str)
- Return type:
bytes
- ngapp.utils.zip_modules(
- modules: list[str],
- dist_info: bool = False,
- exclude_backend: bool = True,
Zip a list of python modules and return the zip file as a bytes object; with dist_info the zip carries the metadata of their distributions, exclude_backend drops all paths containing “backend” (browser packages)
- Parameters:
modules (list[str])
dist_info (bool)
exclude_backend (bool)
- Return type:
bytes