Skip to content

Python API (autogenerated)

This page is populated via mkdocstrings.

New formatted uptime helpers

The plugin exposes a few convenience formatting functions in the public API usable by other plugins or scripts:

  • format_uptime(seconds: float) -> str - full human-readable form (e.g. "1d 2h 3m 4s").
  • format_uptime_dhm(seconds: float) -> str - days/hours/minutes (omits seconds).
  • format_uptime_dh(seconds: float) -> str - days/hours (e.g. "1d 2h").
  • format_uptime_d(seconds: float) -> str - whole days only (e.g. "3d").

Example usage from a Python context inside OctoPrint:

from octoprint_uptime.plugin import format_uptime_dhm

print(format_uptime_dhm(93784))  # -> "1d 2h 3m"

OctoPrint-Uptime plugin package.

Displays host system and OctoPrint process uptime in the navbar and exposes a small JSON API returning both raw seconds and formatted variants. This module avoids importing OctoPrint/Flask at import-time so it can be packaged and unit-tested without the OctoPrint runtime present.

VERSION module-attribute

VERSION = '0.5.1'

UptimePlugin module-attribute

UptimePlugin = OctoprintUptimePlugin

__all__ module-attribute

__all__ = [
    "VERSION",
    "OctoprintUptimePlugin",
    "UptimePlugin",
    "format_uptime",
    "format_uptime_d",
    "format_uptime_dh",
    "format_uptime_dhm",
]

__plugin_name__ module-attribute

__plugin_name__ = 'OctoPrint-Uptime'

__plugin_version__ module-attribute

__plugin_version__ = VERSION

__plugin_description__ module-attribute

__plugin_description__ = "Adds system uptime to the navbar and exposes a small uptime API."

__plugin_author__ module-attribute

__plugin_author__ = 'Ajimaru'

__plugin_url__ module-attribute

__plugin_url__ = (
    "https://github.com/Ajimaru/OctoPrint-Uptime"
)

__plugin_license__ module-attribute

__plugin_license__ = 'AGPLv3'

__plugin_pythoncompat__ module-attribute

__plugin_pythoncompat__ = '>=3.9,<4'

__plugin_implementation__ module-attribute

__plugin_implementation__ = OctoprintUptimePlugin()

OctoprintUptimePlugin

OctoprintUptimePlugin(*args, **kwargs)

Bases: SimpleApiPluginBase, AssetPluginBase, SettingsPluginBase, TemplatePluginBase

OctoPrint plugin implementation.

Uses lazy imports for OctoPrint/Flask integration points so the module can be imported in environments where OctoPrint is not installed.

Initialize internal state for debug, display format, and tracking.

Parameters:

Name Type Description Default
*args object

Positional arguments passed to the parent class.

()
**kwargs object

Keyword arguments passed to the parent class.

{}
Source code in octoprint_uptime/plugin.py
181
182
183
184
185
186
187
188
189
190
191
192
193
def __init__(self, *args: object, **kwargs: object) -> None:
    """Initialize internal state for debug, display format, and tracking.

    Args:
        *args: Positional arguments passed to the parent class.
        **kwargs: Keyword arguments passed to the parent class.
    """
    super().__init__(*args, **kwargs)
    self._debug_enabled: bool = False
    self._display_format: str = "full"
    self._last_debug_time: float = 0.0
    self._debug_throttle_seconds: int = 60
    self._last_uptime_source: Optional[str] = None

get_update_information

get_update_information()

Return metadata for OctoPrint's software update mechanism.

Returns:

Type Description
dict[str, Any]

Update information dictionary keyed by plugin identifier.

Source code in octoprint_uptime/plugin.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
def get_update_information(self) -> dict[str, Any]:
    """Return metadata for OctoPrint's software update mechanism.

    Returns:
        Update information dictionary keyed by plugin identifier.
    """
    return {
        "octoprint_uptime": {
            "displayName": "OctoPrint-Uptime",
            "displayVersion": VERSION,
            "type": "github_release",
            "user": "Ajimaru",
            "repo": "OctoPrint-Uptime",
            "current": VERSION,
            "pip": (
                "https://github.com/Ajimaru/"
                "OctoPrint-Uptime/archive/{target_version}.zip"
            ),
        }
    }

is_api_protected

is_api_protected()

Indicate that the plugin's API endpoint requires authentication.

Returns:

Type Description
bool

Always True; OctoPrint enforces authentication for the endpoint.

Source code in octoprint_uptime/plugin.py
216
217
218
219
220
221
222
def is_api_protected(self) -> bool:
    """Indicate that the plugin's API endpoint requires authentication.

    Returns:
        Always True; OctoPrint enforces authentication for the endpoint.
    """
    return True

get_assets

get_assets()

Return the plugin's static asset files.

Returns:

Type Description
dict[str, list[str]]

Dictionary mapping asset types to file lists.

Source code in octoprint_uptime/plugin.py
224
225
226
227
228
229
230
def get_assets(self) -> dict[str, list[str]]:
    """Return the plugin's static asset files.

    Returns:
        Dictionary mapping asset types to file lists.
    """
    return {"js": ["js/uptime.js"]}

get_template_configs

get_template_configs()

Return template configurations for the navbar and settings panes.

Returns:

Type Description
list[dict[str, Any]]

A list of template configuration dictionaries.

Source code in octoprint_uptime/plugin.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
def get_template_configs(self) -> list[dict[str, Any]]:
    """Return template configurations for the navbar and settings panes.

    Returns:
        A list of template configuration dictionaries.
    """
    return [
        {
            "type": "navbar",
            "name": _("Uptime"),
            "template": "navbar.jinja2",
            "custom_bindings": True,
            # Use OctoPrint's default container id by omitting ``div``.
            # The plugin identifier is ``octoprint_uptime`` (see the
            # entry point), so the default navbar <li> id becomes
            # ``navbar_plugin_octoprint_uptime`` -- the JS selectors must
            # match that exact id. A custom div id breaks the core navbar
            # reordering feature: it persists order in
            # ``appearance.components.order.navbar`` keyed by
            # ``plugin_<identifier>`` and looks the element up by the
            # default id, so a non-standard id makes the item snap back to
            # its default position on reload. OctoPrint already wraps the
            # template in the navbar <li>, so the template must not add its
            # own.
        },
        {
            "type": "settings",
            "name": _("Uptime"),
            "template": "settings.jinja2",
            "custom_bindings": False,
        },
    ]

is_template_autoescaped

is_template_autoescaped()

Indicate that the plugin's templates are autoescaped.

Returns:

Type Description
bool

Always True.

Source code in octoprint_uptime/plugin.py
265
266
267
268
269
270
271
def is_template_autoescaped(self) -> bool:
    """Indicate that the plugin's templates are autoescaped.

    Returns:
        Always True.
    """
    return True

_get_uptime_seconds

_get_uptime_seconds()

Retrieve system uptime, trying /proc first and psutil second.

Returns:

Type Description
Optional[float]

Tuple (seconds, source) where source is one of "proc",

str

"psutil" or "none"; seconds is None when unavailable.

Source code in octoprint_uptime/plugin.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def _get_uptime_seconds(self) -> tuple[Optional[float], str]:
    """Retrieve system uptime, trying /proc first and psutil second.

    Returns:
        Tuple ``(seconds, source)`` where ``source`` is one of ``"proc"``,
        ``"psutil"`` or ``"none"``; ``seconds`` is None when unavailable.
    """
    uptime = self._get_uptime_from_proc()
    if uptime is not None:
        self._last_uptime_source = "proc"
        return uptime, "proc"

    uptime = self._get_uptime_from_psutil()
    if uptime is not None:
        self._last_uptime_source = "psutil"
        return uptime, "psutil"

    self._last_uptime_source = "none"
    return None, "none"

_get_uptime_from_proc

_get_uptime_from_proc()

Get system uptime from /proc/uptime if available.

Source code in octoprint_uptime/plugin.py
293
294
295
296
297
298
299
300
301
def _get_uptime_from_proc(self) -> Optional[float]:
    """Get system uptime from /proc/uptime if available."""
    try:
        if os.path.exists("/proc/uptime"):
            with open("/proc/uptime", encoding="utf-8") as f:
                return float(f.readline().split()[0])
    except (ValueError, TypeError, OSError, IndexError):
        pass
    return None

_get_uptime_from_psutil

_get_uptime_from_psutil()

Get system uptime from psutil's boot time if psutil is available.

Source code in octoprint_uptime/plugin.py
303
304
305
306
307
308
309
310
311
312
313
314
315
def _get_uptime_from_psutil(self) -> Optional[float]:
    """Get system uptime from psutil's boot time if psutil is available."""
    try:
        _ps = importlib.import_module("psutil")
    except ImportError:
        return None
    try:
        uptime = time.time() - _ps.boot_time()
    except (AttributeError, TypeError, ValueError, OSError):
        return None
    if 0 <= uptime < _MAX_UPTIME_SECONDS:
        return uptime
    return None

_get_octoprint_uptime_from_proc

_get_octoprint_uptime_from_proc()

Get process uptime from /proc on Linux in a clock-jump-safe way.

Source code in octoprint_uptime/plugin.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def _get_octoprint_uptime_from_proc(self) -> Optional[float]:
    """Get process uptime from /proc on Linux in a clock-jump-safe way."""
    try:
        if not (
            os.path.exists("/proc/uptime") and os.path.exists("/proc/self/stat")
        ):
            return None

        with open("/proc/uptime", encoding="utf-8") as f_uptime:
            system_uptime = float(f_uptime.readline().split()[0])

        with open("/proc/self/stat", encoding="utf-8") as f_stat:
            stat_line = f_stat.readline().strip()

        # /proc/self/stat contains "pid (comm) ..." where comm can include
        # spaces, so split only after the closing parenthesis. Field 22
        # (starttime, in clock ticks since boot) is then at index 19.
        rparen = stat_line.rfind(")")
        if rparen == -1:
            return None
        stat_fields = stat_line[rparen + 2 :].split()
        if len(stat_fields) <= 19:
            return None

        start_ticks = float(stat_fields[19])
        clk_tck = float(os.sysconf("SC_CLK_TCK"))
        if clk_tck <= 0:
            return None

        process_uptime = system_uptime - (start_ticks / clk_tck)
        if 0 <= process_uptime < _MAX_UPTIME_SECONDS:
            return process_uptime
    except (ValueError, TypeError, OSError):
        return None
    return None

_get_octoprint_uptime

_get_octoprint_uptime()

Get OctoPrint process uptime, preferring /proc and then psutil.

Source code in octoprint_uptime/plugin.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def _get_octoprint_uptime(self) -> Optional[float]:
    """Get OctoPrint process uptime, preferring /proc and then psutil."""
    proc_uptime = self._get_octoprint_uptime_from_proc()
    if proc_uptime is not None:
        return proc_uptime

    try:
        _ps = importlib.import_module("psutil")
    except ImportError:
        return None

    handled = (AttributeError, TypeError, ValueError, OSError)
    psutil_error = getattr(_ps, "Error", None)
    if isinstance(psutil_error, type) and issubclass(psutil_error, BaseException):
        handled += (psutil_error,)

    try:
        create_time = _ps.Process(os.getpid()).create_time()
        uptime = time.time() - create_time
    except handled:
        return None
    if 0 <= uptime < _MAX_UPTIME_SECONDS:
        return uptime
    return None

on_settings_initialized

on_settings_initialized()

Update internal state once OctoPrint has initialized settings.

Also calls a base implementation if OctoPrint provides one.

Source code in octoprint_uptime/plugin.py
378
379
380
381
382
383
384
385
386
387
388
389
390
def on_settings_initialized(self) -> None:
    """Update internal state once OctoPrint has initialized settings.

    Also calls a base implementation if OctoPrint provides one.
    """
    self._safe_update_internal_state()

    hook = getattr(super(), "on_settings_initialized", None)
    if not callable(hook):
        hook = getattr(SettingsPluginBase, "on_settings_initialized", None)

    if callable(hook):
        self._invoke_settings_hook(hook)

on_settings_save

on_settings_save(data)

Sanitize, persist, and apply the plugin settings.

Parameters:

Name Type Description Default
data dict[str, Any]

Settings data to save.

required
Source code in octoprint_uptime/plugin.py
392
393
394
395
396
397
398
399
400
401
402
def on_settings_save(self, data: dict[str, Any]) -> None:
    """Sanitize, persist, and apply the plugin settings.

    Args:
        data: Settings data to save.
    """
    self._validate_and_sanitize_settings(data)
    self._log_settings_save_data(data)
    self._call_base_on_settings_save(data)
    self._update_internal_state()
    self._log_settings_after_save()

_safe_update_internal_state

_safe_update_internal_state()

Update internal state, logging expected failures instead of raising.

Source code in octoprint_uptime/plugin.py
404
405
406
407
408
409
410
411
412
413
414
def _safe_update_internal_state(self) -> None:
    """Update internal state, logging expected failures instead of raising."""
    logger = getattr(self, "_logger", None)
    try:
        self._update_internal_state()
    except (AttributeError, KeyError, ValueError) as e:
        if logger:
            logger.warning(
                "on_settings_initialized: failed to update internal state: %s",
                e,
            )

_get_hook_positional_param_count

_get_hook_positional_param_count(hook)

Return the number of positional params a callable accepts.

Parameters:

Name Type Description Default
hook Any

The callable to inspect.

required

Returns:

Type Description
Optional[int]

The positional parameter count, or None when the signature cannot

Optional[int]

be inspected (logged as info).

Source code in octoprint_uptime/plugin.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
def _get_hook_positional_param_count(self, hook: Any) -> Optional[int]:
    """Return the number of positional params a callable accepts.

    Args:
        hook: The callable to inspect.

    Returns:
        The positional parameter count, or None when the signature cannot
        be inspected (logged as info).
    """
    logger = getattr(self, "_logger", None)
    try:
        sig = inspect.signature(hook)
        params = [
            p
            for p in sig.parameters.values()
            if p.kind
            in (
                inspect.Parameter.POSITIONAL_ONLY,
                inspect.Parameter.POSITIONAL_OR_KEYWORD,
            )
        ]
        return len(params)
    except (ValueError, TypeError, AttributeError) as e:
        if logger:
            logger.info(
                "_get_hook_positional_param_count: "
                "unable to inspect signature for %r: %s",
                hook,
                e,
            )
        return None

_safe_invoke_hook

_safe_invoke_hook(hook, param_count)

Invoke a hook with zero or one positional parameter, logging failures.

Parameters:

Name Type Description Default
hook Any

The callable to invoke.

required
param_count int

0 or 1; any exception raised by the hook is logged but not propagated.

required
Source code in octoprint_uptime/plugin.py
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
def _safe_invoke_hook(self, hook: Any, param_count: int) -> None:
    """Invoke a hook with zero or one positional parameter, logging failures.

    Args:
        hook: The callable to invoke.
        param_count: 0 or 1; any exception raised by the hook is logged
            but not propagated.
    """
    logger = getattr(self, "_logger", None)
    try:
        if param_count == 0:
            hook()
        else:
            hook(self)
    except (RuntimeError, AttributeError, TypeError, ValueError):
        if logger:
            logger.exception("_safe_invoke_hook: %r raised", hook)

_invoke_settings_hook

_invoke_settings_hook(hook)

Invoke a settings hook using signature inspection.

Skips the call (with a warning) when the hook expects an unexpected number of positional parameters or its signature cannot be inspected.

Parameters:

Name Type Description Default
hook Any

The callable to invoke.

required
Source code in octoprint_uptime/plugin.py
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def _invoke_settings_hook(self, hook: Any) -> None:
    """Invoke a settings hook using signature inspection.

    Skips the call (with a warning) when the hook expects an unexpected
    number of positional parameters or its signature cannot be inspected.

    Args:
        hook: The callable to invoke.
    """
    logger = getattr(self, "_logger", None)

    param_count = self._get_hook_positional_param_count(hook)
    if param_count is None:
        return
    if param_count not in (0, 1):
        if logger:
            logger.warning(
                "_invoke_settings_hook: unexpected parameter count "
                "%s for %r; skipping",
                param_count,
                hook,
            )
        return

    self._safe_invoke_hook(hook, param_count)

_validate_and_sanitize_settings

_validate_and_sanitize_settings(data)

Coerce and clamp integer settings in the provided save payload.

Missing or non-integer values are replaced with their defaults, valid values are clamped to the allowed range (see _INT_SETTING_BOUNDS).

Parameters:

Name Type Description Default
data dict[str, Any]

The settings payload passed to on_settings_save.

required
Source code in octoprint_uptime/plugin.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
def _validate_and_sanitize_settings(self, data: dict[str, Any]) -> None:
    """Coerce and clamp integer settings in the provided save payload.

    Missing or non-integer values are replaced with their defaults, valid
    values are clamped to the allowed range (see ``_INT_SETTING_BOUNDS``).

    Args:
        data: The settings payload passed to ``on_settings_save``.
    """
    plugins = data.get("plugins") if isinstance(data, dict) else None
    if not isinstance(plugins, dict):
        return
    uptime_cfg = plugins.get("octoprint_uptime")
    if not isinstance(uptime_cfg, dict):
        return
    for key, (default, lo, hi) in _INT_SETTING_BOUNDS.items():
        if key not in uptime_cfg:
            continue
        raw = uptime_cfg.get(key)
        try:
            val = default if raw is None else int(raw)
        except (ValueError, TypeError):
            val = default
        uptime_cfg[key] = max(lo, min(val, hi))

_log_settings_save_data

_log_settings_save_data(data)

Log the payload passed to the settings save event for debugging.

Parameters:

Name Type Description Default
data dict[str, Any]

The data being saved to the settings.

required
Source code in octoprint_uptime/plugin.py
518
519
520
521
522
523
524
525
526
527
528
529
def _log_settings_save_data(self, data: dict[str, Any]) -> None:
    """Log the payload passed to the settings save event for debugging.

    Args:
        data: The data being saved to the settings.
    """
    logger = getattr(self, "_logger", None)
    if logger:
        try:
            logger.debug("on_settings_save data: %r", data)
        except (AttributeError, TypeError, ValueError):
            pass

_call_base_on_settings_save

_call_base_on_settings_save(data)

Call the base class on_settings_save, if available.

Parameters:

Name Type Description Default
data dict[str, Any]

The settings data to be saved.

required
Source code in octoprint_uptime/plugin.py
531
532
533
534
535
536
537
538
539
540
541
542
def _call_base_on_settings_save(self, data: dict[str, Any]) -> None:
    """Call the base class ``on_settings_save``, if available.

    Args:
        data: The settings data to be saved.
    """
    method = getattr(SettingsPluginBase, "on_settings_save", None)
    if callable(method):
        try:
            method(self, data)
        except (AttributeError, TypeError, ValueError):
            pass

get_settings_defaults

get_settings_defaults()

Return default settings for the plugin.

OctoPrint populates settings.plugins.<identifier> from this mapping so the frontend can safely bind to settings.plugins.octoprint_uptime.*.

Returns:

Type Description
dict[str, Any]

Mapping of setting names to default values.

Source code in octoprint_uptime/plugin.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
def get_settings_defaults(self) -> dict[str, Any]:
    """Return default settings for the plugin.

    OctoPrint populates ``settings.plugins.<identifier>`` from this mapping
    so the frontend can safely bind to
    ``settings.plugins.octoprint_uptime.*``.

    Returns:
        Mapping of setting names to default values.
    """
    return {
        "debug": False,
        "show_system_uptime": True,
        "show_octoprint_uptime": True,
        "compact_display": False,
        "compact_toggle_interval_seconds": 5,
        "icon_only": False,
        "display_format": "full",
        "debug_throttle_seconds": 60,
        "poll_interval_seconds": 5,
    }

_update_internal_state

_update_internal_state()

Refresh cached debug, display format, and throttle values.

Source code in octoprint_uptime/plugin.py
566
567
568
569
570
571
572
def _update_internal_state(self) -> None:
    """Refresh cached debug, display format, and throttle values."""
    self._debug_enabled = bool(self._settings.get(["debug"]))
    self._display_format = str(self._settings.get(["display_format"]))
    self._debug_throttle_seconds = int(
        self._settings.get(["debug_throttle_seconds"]) or 60
    )

_log_settings_after_save

_log_settings_after_save()

Log the effective settings after they have been saved.

Source code in octoprint_uptime/plugin.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def _log_settings_after_save(self) -> None:
    """Log the effective settings after they have been saved."""
    logger = getattr(self, "_logger", None)
    if not logger:
        return
    try:
        logger.info(
            "UptimePlugin: settings after save: debug=%s, "
            "display_format=%s, "
            "debug_throttle_seconds=%s",
            self._debug_enabled,
            self._display_format,
            self._debug_throttle_seconds,
        )
    except (AttributeError, TypeError, ValueError):
        pass

_log_debug

_log_debug(message)

Log a debug message when enabled, throttled to avoid log spam.

Messages are dropped while _debug_throttle_seconds has not elapsed since the last logged message. Logging errors are silently ignored.

Parameters:

Name Type Description Default
message str

The debug message to log.

required
Source code in octoprint_uptime/plugin.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
def _log_debug(self, message: str) -> None:
    """Log a debug message when enabled, throttled to avoid log spam.

    Messages are dropped while ``_debug_throttle_seconds`` has not elapsed
    since the last logged message. Logging errors are silently ignored.

    Args:
        message: The debug message to log.
    """
    try:
        if not getattr(self, "_debug_enabled", False):
            return
        now = time.time()
        last_time = getattr(self, "_last_debug_time", 0)
        if (now - last_time) < self._debug_throttle_seconds:
            return
        self._last_debug_time = now
        try:
            self._logger.debug(message)
        except (AttributeError, TypeError, ValueError):
            pass
    except (AttributeError, TypeError, ValueError):
        pass

_fallback_uptime_response

_fallback_uptime_response()

Build a system-uptime-only response as a JSON or dict payload.

Defensive fallback used when the full API response cannot be built. Returns a Flask JSON response when Flask is available, a plain dict otherwise; on error the uptime is reported as unknown.

Source code in octoprint_uptime/plugin.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
def _fallback_uptime_response(self) -> Any:
    """Build a system-uptime-only response as a JSON or dict payload.

    Defensive fallback used when the full API response cannot be built.
    Returns a Flask JSON response when Flask is available, a plain dict
    otherwise; on error the uptime is reported as unknown.
    """
    logger = getattr(self, "_logger", None)
    try:
        seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d = (
            self._get_uptime_info()
        )
        uptime_available = (
            isinstance(seconds, (int, float))
            and seconds >= 0
            and uptime_full != _("unknown")
        )
        if _flask is None:
            resp = {"uptime": uptime_full, "uptime_available": uptime_available}
            if not uptime_available:
                resp["uptime_note"] = _(
                    "Uptime could not be determined on this system."
                )
            return resp

        display_format, poll_interval = self._get_api_settings()
        resp = {
            "uptime": uptime_full,
            "uptime_dhm": uptime_dhm,
            "uptime_dh": uptime_dh,
            "uptime_d": uptime_d,
            "seconds": seconds,
            "display_format": display_format,
            "poll_interval_seconds": poll_interval,
            "uptime_available": uptime_available,
        }
        if not uptime_available:
            resp["uptime_note"] = _(
                "Uptime could not be determined on this system."
            )
        try:
            return _flask.jsonify(**resp)
        except (TypeError, ValueError, RuntimeError):
            if logger:
                logger.exception(
                    "_fallback_uptime_response: flask.jsonify failed, "
                    "falling back to dict"
                )
            return resp
    except (AttributeError, TypeError, ValueError):
        if logger:
            try:
                logger.exception(
                    "_fallback_uptime_response: unexpected error while "
                    "building response"
                )
            except (AttributeError, TypeError, ValueError):
                pass
        return {"uptime": _("unknown"), "uptime_available": False}

on_api_get

on_api_get(_request=None)

Handle GET requests to the plugin's API endpoint.

Parameters:

Name Type Description Default
_request Any

The incoming request (unused).

None

Returns:

Type Description
Any

A Flask JSON response with all uptime variants when Flask is

Any

available, a reduced plain dict otherwise, or an error response

Any

when the permission check fails.

Source code in octoprint_uptime/plugin.py
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
def on_api_get(self, _request: Any = None) -> Any:
    """Handle GET requests to the plugin's API endpoint.

    Args:
        _request: The incoming request (unused).

    Returns:
        A Flask JSON response with all uptime variants when Flask is
        available, a reduced plain dict otherwise, or an error response
        when the permission check fails.
    """
    permission_result = self._handle_permission_check()
    if permission_result is not None:
        return permission_result

    seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d = self._get_uptime_info()
    (
        octoprint_seconds,
        octoprint_uptime_full,
        octoprint_uptime_dhm,
        octoprint_uptime_dh,
        octoprint_uptime_d,
    ) = self._get_octoprint_uptime_info()
    self._log_debug(_("Uptime API requested, result=%s") % uptime_full)

    if _flask is not None:
        display_format, poll_interval = self._get_api_settings()
        # The frontend (navbar widget and settings note) keys off
        # ``uptime_available`` to show its "Unavailable" fallback state.
        uptime_available = (
            isinstance(seconds, (int, float))
            and seconds >= 0
            and uptime_full != _("unknown")
        )
        payload: dict[str, Any] = {
            "uptime": uptime_full,
            "uptime_dhm": uptime_dhm,
            "uptime_dh": uptime_dh,
            "uptime_d": uptime_d,
            "seconds": seconds,
            "octoprint_uptime": octoprint_uptime_full,
            "octoprint_uptime_dhm": octoprint_uptime_dhm,
            "octoprint_uptime_dh": octoprint_uptime_dh,
            "octoprint_uptime_d": octoprint_uptime_d,
            "octoprint_seconds": octoprint_seconds,
            "display_format": display_format,
            "poll_interval_seconds": poll_interval,
            "uptime_available": uptime_available,
        }
        if not uptime_available:
            payload["uptime_note"] = _(
                "Uptime could not be determined on this system."
            )
        return _flask.jsonify(**payload)

    return {"uptime": uptime_full, "octoprint_uptime": octoprint_uptime_full}

_handle_permission_check

_handle_permission_check()

Check permissions for API GET requests, handling errors.

Returns:

Type Description
Optional[Any]

A forbidden/fallback response when permission is denied or the

Optional[Any]

check errors out, otherwise None when permission is granted.

Source code in octoprint_uptime/plugin.py
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
def _handle_permission_check(self) -> Optional[Any]:
    """Check permissions for API GET requests, handling errors.

    Returns:
        A forbidden/fallback response when permission is denied or the
        check errors out, otherwise None when permission is granted.
    """
    try:
        if not self._check_permissions():
            try:
                return self._abort_forbidden()
            except (AttributeError, TypeError, ValueError, RuntimeError, OSError):
                return {"error": _("Forbidden"), "uptime_available": False}
    except (AttributeError, TypeError, ValueError):
        if getattr(self, "_logger", None) is not None:
            self._logger.exception(
                "on_api_get: unexpected error while checking permissions"
            )
        try:
            return self._abort_forbidden()
        except (AttributeError, TypeError, ValueError, RuntimeError, OSError):
            return {"error": _("Forbidden"), "uptime_available": False}
    return None

_check_permissions

_check_permissions()

Check whether the current user may query the uptime API.

Returns:

Type Description
bool

Always True for now: fine-grained permission enforcement is not

bool

implemented; OctoPrint's API authentication already gates access.

bool

Replace with real checks when needed.

Source code in octoprint_uptime/plugin.py
756
757
758
759
760
761
762
763
764
def _check_permissions(self) -> bool:
    """Check whether the current user may query the uptime API.

    Returns:
        Always True for now: fine-grained permission enforcement is not
        implemented; OctoPrint's API authentication already gates access.
        Replace with real checks when needed.
    """
    return True

_abort_forbidden

_abort_forbidden()

Abort with HTTP 403 when Flask is available.

Returns:

Type Description
dict[str, str]

An error dict when Flask is unavailable (otherwise Flask's abort

dict[str, str]

raises before the return).

Source code in octoprint_uptime/plugin.py
766
767
768
769
770
771
772
773
774
775
def _abort_forbidden(self) -> dict[str, str]:
    """Abort with HTTP 403 when Flask is available.

    Returns:
        An error dict when Flask is unavailable (otherwise Flask's abort
        raises before the return).
    """
    if _flask is not None:
        _flask.abort(403)
    return {"error": _("Forbidden")}

_get_uptime_info

_get_uptime_info()

Retrieve system uptime and its formatted display strings.

Honors a get_uptime_seconds attribute when one has been injected (e.g. by tests or subclasses), otherwise uses the built-in sources.

Returns:

Type Description
tuple[Optional[float], str, str, str, str]

Tuple (seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d).

Source code in octoprint_uptime/plugin.py
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
def _get_uptime_info(self) -> tuple[Optional[float], str, str, str, str]:
    """Retrieve system uptime and its formatted display strings.

    Honors a ``get_uptime_seconds`` attribute when one has been injected
    (e.g. by tests or subclasses), otherwise uses the built-in sources.

    Returns:
        Tuple ``(seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d)``.
    """
    try:
        if hasattr(self, "get_uptime_seconds") and callable(
            self.get_uptime_seconds
        ):
            res = self.get_uptime_seconds()
            if isinstance(res, tuple) and len(res) == 2:
                seconds, _source = res
                self._last_uptime_source = _source
            else:
                seconds = res
                self._last_uptime_source = "custom"
        else:
            seconds, _source = self._get_uptime_seconds()
        uptime_seconds: Optional[float] = (
            seconds if isinstance(seconds, (int, float, type(None))) else None
        )
        return self._format_uptime_tuple(uptime_seconds)
    except (AttributeError, TypeError, ValueError):
        try:
            self._logger.exception(_("Error computing uptime"))
        except (AttributeError, TypeError, ValueError):
            pass
        return self._format_uptime_tuple(None)

_format_uptime_tuple

_format_uptime_tuple(seconds)

Normalize and format an uptime value into display strings.

Parameters:

Name Type Description Default
seconds Optional[float]

The uptime in seconds, or None/invalid when unknown.

required

Returns:

Type Description
Optional[float]

Tuple (seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d);

str

all strings are the localized "unknown" when seconds is invalid.

Source code in octoprint_uptime/plugin.py
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
def _format_uptime_tuple(
    self, seconds: Optional[float]
) -> tuple[Optional[float], str, str, str, str]:
    """Normalize and format an uptime value into display strings.

    Args:
        seconds: The uptime in seconds, or None/invalid when unknown.

    Returns:
        Tuple ``(seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d)``;
        all strings are the localized "unknown" when seconds is invalid.
    """
    if isinstance(seconds, (int, float)):
        seconds = float(seconds)
    else:
        seconds = None

    if seconds is not None:
        uptime_full = format_uptime(seconds)
        uptime_dhm = format_uptime_dhm(seconds)
        uptime_dh = format_uptime_dh(seconds)
        uptime_d = format_uptime_d(seconds)
    else:
        uptime_full = uptime_dhm = uptime_dh = uptime_d = _("unknown")
    return seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d

_get_octoprint_uptime_info

_get_octoprint_uptime_info()

Retrieve OctoPrint process uptime and its formatted display strings.

Returns:

Type Description
tuple[Optional[float], str, str, str, str]

Tuple (seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d).

Source code in octoprint_uptime/plugin.py
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
def _get_octoprint_uptime_info(self) -> tuple[Optional[float], str, str, str, str]:
    """Retrieve OctoPrint process uptime and its formatted display strings.

    Returns:
        Tuple ``(seconds, uptime_full, uptime_dhm, uptime_dh, uptime_d)``.
    """
    try:
        seconds = self._get_octoprint_uptime()
        return self._format_uptime_tuple(seconds)
    except (AttributeError, TypeError, ValueError):
        try:
            self._logger.exception(_("Error computing OctoPrint uptime"))
        except (AttributeError, TypeError, ValueError):
            pass
        return self._format_uptime_tuple(None)

_get_api_settings

_get_api_settings()

Read the display format and poll interval for API responses.

Returns:

Type Description
str

Tuple (display_format, poll_interval_seconds).

int

display_format falls back to "full" and the poll interval

tuple[str, int]

is defaulted and clamped to its allowed range when missing or

tuple[str, int]

invalid.

Source code in octoprint_uptime/plugin.py
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
def _get_api_settings(self) -> tuple[str, int]:
    """Read the display format and poll interval for API responses.

    Returns:
        Tuple ``(display_format, poll_interval_seconds)``.
        ``display_format`` falls back to ``"full"`` and the poll interval
        is defaulted and clamped to its allowed range when missing or
        invalid.
    """
    logger = getattr(self, "_logger", None)

    display_format = "full"
    try:
        raw_fmt = self._settings.get(["display_format"])
        if raw_fmt is None:
            if logger:
                logger.debug(
                    "_get_api_settings: display_format missing, "
                    "defaulting to 'full'"
                )
        else:
            display_format = str(raw_fmt)
    except (AttributeError, TypeError, ValueError):
        if logger:
            logger.exception(
                "_get_api_settings: failed to read display_format, "
                "defaulting to 'full'"
            )

    default_poll, poll_min, poll_max = _INT_SETTING_BOUNDS["poll_interval_seconds"]
    poll_interval = default_poll
    try:
        raw_poll = self._settings.get(["poll_interval_seconds"])
        if raw_poll is None or raw_poll == "":
            if logger:
                logger.debug(
                    "_get_api_settings: poll_interval_seconds missing, "
                    "defaulting to %s",
                    default_poll,
                )
        else:
            try:
                poll_interval = int(raw_poll)
            except (TypeError, ValueError):
                if logger:
                    logger.debug(
                        "_get_api_settings: poll_interval_seconds invalid "
                        "(%r), defaulting to %s",
                        raw_poll,
                        default_poll,
                    )
        clamped = max(poll_min, min(poll_interval, poll_max))
        if clamped != poll_interval and logger:
            logger.debug(
                "_get_api_settings: poll_interval_seconds %s out of range, "
                "clamping to %s",
                poll_interval,
                clamped,
            )
        poll_interval = clamped
    except (AttributeError, TypeError, ValueError):
        poll_interval = default_poll
        if logger:
            logger.exception(
                "_get_api_settings: failed to read poll_interval_seconds, "
                "defaulting to %s",
                default_poll,
            )

    return display_format, poll_interval

format_uptime

format_uptime(seconds)

Format a duration as days, hours, minutes, and seconds.

Parameters:

Name Type Description Default
seconds float

The total number of seconds to format.

required

Returns:

Type Description
str

The duration as e.g. '1d 2h 3m 4s'. Leading zero units are

str

omitted, so 61 becomes '1m 1s'.

Source code in octoprint_uptime/plugin.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
def format_uptime(seconds: float) -> str:
    """Format a duration as days, hours, minutes, and seconds.

    Args:
        seconds: The total number of seconds to format.

    Returns:
        The duration as e.g. ``'1d 2h 3m 4s'``. Leading zero units are
        omitted, so ``61`` becomes ``'1m 1s'``.
    """
    days, hours, minutes, secs = _split_uptime(seconds)
    parts = []
    if days:
        parts.append(f"{days}d")
    if hours or days:
        parts.append(f"{hours}h")
    if minutes or hours or days:
        parts.append(f"{minutes}m")
    parts.append(f"{secs}s")
    return " ".join(parts)

format_uptime_d

format_uptime_d(seconds)

Format a duration as whole days.

Parameters:

Name Type Description Default
seconds float

The total number of seconds to format.

required

Returns:

Type Description
str

The number of whole days followed by 'd', e.g. '2d'.

Source code in octoprint_uptime/plugin.py
156
157
158
159
160
161
162
163
164
165
166
def format_uptime_d(seconds: float) -> str:
    """Format a duration as whole days.

    Args:
        seconds: The total number of seconds to format.

    Returns:
        The number of whole days followed by ``'d'``, e.g. ``'2d'``.
    """
    days, _hours, _minutes, _secs = _split_uptime(seconds)
    return f"{days}d"

format_uptime_dh

format_uptime_dh(seconds)

Format a duration as days and hours.

Parameters:

Name Type Description Default
seconds float

The total number of seconds to format.

required

Returns:

Type Description
str

'Xd Yh' when days are present, otherwise 'Yh'.

Source code in octoprint_uptime/plugin.py
141
142
143
144
145
146
147
148
149
150
151
152
153
def format_uptime_dh(seconds: float) -> str:
    """Format a duration as days and hours.

    Args:
        seconds: The total number of seconds to format.

    Returns:
        ``'Xd Yh'`` when days are present, otherwise ``'Yh'``.
    """
    days, hours, _minutes, _secs = _split_uptime(seconds)
    if days:
        return f"{days}d {hours}h"
    return f"{hours}h"

format_uptime_dhm

format_uptime_dhm(seconds)

Format a duration as days, hours, and minutes.

Parameters:

Name Type Description Default
seconds float

The total number of seconds to format.

required

Returns:

Type Description
str

'Xd Yh Zm' when days are present, otherwise 'Yh Zm'.

Source code in octoprint_uptime/plugin.py
126
127
128
129
130
131
132
133
134
135
136
137
138
def format_uptime_dhm(seconds: float) -> str:
    """Format a duration as days, hours, and minutes.

    Args:
        seconds: The total number of seconds to format.

    Returns:
        ``'Xd Yh Zm'`` when days are present, otherwise ``'Yh Zm'``.
    """
    days, hours, minutes, _secs = _split_uptime(seconds)
    if days:
        return f"{days}d {hours}h {minutes}m"
    return f"{hours}h {minutes}m"

API changes: uptime availability

When uptime cannot be determined the plugin API now includes an uptime_available boolean and an optional uptime_note string that can contain a localized hint. Example response:

{
  "uptime": "unknown",
  "uptime_available": false,
  "uptime_note": "Uptime could not be determined."
}

Frontend callers: when querying the plugin from JavaScript inside the OctoPrint UI prefer the OctoPrint helper and pass the plugin id only, for example:

OctoPrint.simpleApiGet("octoprint_uptime").done(function (data) {
  /* ... */
});