Skip to content

Python API ​

python
from axon import (
    class AxonGUI(web_name: WebName, url: str, options: Optional[AxonGUIOptions] = None)AxonGUI, AxonController(web_name: str | list[str] = '*', id: Optional[str] = None, shared: bool = False)
``AxonController`` 的命名空间对象:既能当装饰器用,也挂注册表操作。
AxonController
, class Axon(web_name: str)Axon, AxonCall: AxonCallNamespace · broadcast / call / getVar / setVarAxonCall,
AxonEvent · add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent, class AxonStore(id: str, *web_names, auto_create: bool = True)AxonStore, class AxonMagicGUIAxonMagicGUI, )

The distribution name is axon-gui; the import name is axon.

AxonGUI — the window ​

python
from PySide6.QtWidgets import class QApplicationQApplication
from axon import class AxonGUI(web_name: WebName, url: str, options: Optional[AxonGUIOptions] = None)AxonGUI

app = class QApplicationQApplication(sys.argv)
view = class AxonGUI(web_name: WebName, url: str, options: Optional[AxonGUIOptions] = None)AxonGUI("MainView", "http://127.0.0.1:8000/")   # window name + page URL
view.resize(1200, 700)
view.show()
app.exec()
ArgumentMeaning
web_namewindow name, unique in the process; controllers and Axon("...") use it to find the window
urlpage URL, http:// or file://
options{"disable_native_context_menu": True} turns off the native Qt context menu so the page can draw its own; crash_recovery / crash_reload_limit control what happens after a crash (see "After a crash")
Method / attributeMeaning
get_web(web_name)get a created window (class method)
windows()names of all open windows
registerChannel(id, obj)expose an extra QObject to the page
web_namethe window name

Once the page has loaded and the JS channel is ready, the loadFinished event is dispatched to the page.

After a crash ​

When the renderer process dies (the window is still there, the page process is gone), Axon does three things instead of leaving you with a blank window:

  1. every call to that window that is still waiting for a reply fails immediately with AxonChannelLostError (CHANNEL_LOST) — previously they hung forever unless you passed timeout;
  2. the renderProcessCrashed event is dispatched on the Python side;
  3. by default the page is reloaded, the channel re-handshakes, and calls work again. Current state lives on view.render_crashed / view.last_crash.
from axon import AxonEvent

AxonEvent.add_listener(
    "renderProcessCrashed",
    lambda info: print(f"{info['webName']} crashed: {info['status']}, {info['failedCalls']} calls dropped"),
)

Event payload: webName, status (e.g. KilledTerminationStatus), exitCode, failedCalls, willReload.

Reloads are capped (3 in a row by default) and the counter only clears after the page has been stable for 5 seconds, so a crash-reload-crash loop stops itself. To take over the policy:

view = AxonGUI("MainView", url, options={"crash_recovery": "none"})

With "none" Axon only records the state and dispatches the event, and does not reload.

AxonController — letting JS call Python ​

python
from axon import AxonController(web_name: str | list[str] = '*', id: Optional[str] = None, shared: bool = False)
``AxonController`` 的命名空间对象:既能当装饰器用,也挂注册表操作。
AxonController
@AxonController(web_name: str | list[str] = '*', id: Optional[str] = None, shared: bool = False)
``AxonController`` 的命名空间对象:既能当装饰器用,也挂注册表操作。
AxonController
("MainView") # available in this window only
class class CalcCalc: def add(self, a: int, b: int) -> int: return a + b @AxonController(web_name: str | list[str] = '*', id: Optional[str] = None, shared: bool = False)
``AxonController`` 的命名空间对象:既能当装饰器用,也挂注册表操作。
AxonController
() # available in every window, name = class name
class class CommonCommon: ...

Signature: AxonController(web_name="*", id=None, shared=False)

ArgumentMeaning
web_namea string or a list; "*" means every window (including windows created later)
idcontroller name, defaults to the class name; JS calls Axon.<id>.<method>
sharedwhen True, all windows share one instance

Instances are created lazily when the window (or the controller) is set up. Methods come in two flavours:

  • def method(...) → runs on the worker pool
  • async def method(...) → runs on the asyncio event loop

Axon — calling JS ​

python
from axon import class Axon(web_name: str)Axon

js = class Axon(web_name: str)Axon("MainView")              # window name

js.DocsJS.mirror({"hello": "world"}).result(5)   # call and wait for the result (seconds)
js.DocsJS.value.get(5)                            # read a JS property
js.DocsJS.value = 99                              # write a JS property (send and forget)

.result() or await? ​

There is exactly one thing to check: is the function you are in an async def?

python
@AxonController("MainView")
class class DemoDemo:
    def sync_method(self):                    # plain def -> use .result(timeout seconds)
        return Axon("MainView").DocsJS.mirror({"a": 1}).result(5)

    async def async_method(self):             # async def -> use await
        return await Axon("MainView").DocsJS.mirror({"a": 1})

await inside a plain def is a syntax error; .result() inside an async def blocks the event-loop thread (other coroutines on the same loop cannot run while it waits). So this is not a style choice, the pairing is mandatory.

FormMeaning
js.Ctrl.fn(*args, kwargs={...})returns an AxonFuture
js.Ctrl.fn(...).result(timeout)wait synchronously, raises on timeout
await js.Ctrl.fn(...)wait asynchronously
js.Ctrl.prop.get(timeout)read a property
js.Ctrl.prop = vwrite a property

If the window does not exist, .result() raises RuntimeError: web 'X' not found; errors thrown in JS arrive as JSRuntimeError.

AxonCall — module-level functions ​

AxonCall is a namespace for four functions, equivalent to importing them directly:

python
from axon import AxonCall: AxonCallNamespace  ·  broadcast / call / getVar / setVarAxonCall

AxonCall: AxonCallNamespace  ·  broadcast / call / getVar / setVarAxonCall.call("MainView", "DocsJS", "mirror", [{"a": 1}])
AxonCall: AxonCallNamespace  ·  broadcast / call / getVar / setVarAxonCall.setVar("MainView", "DocsJS", "value", 99)
AxonCall: AxonCallNamespace  ·  broadcast / call / getVar / setVarAxonCall.getVar("MainView", "DocsJS", "value")
AxonCall: AxonCallNamespace  ·  broadcast / call / getVar / setVarAxonCall.broadcast("DocsJS", "note", ["hi"])       # returns list[Future], one per window

Signatures:

call(web_name, controller_id, func, args=(), kwargs=None)
setVar(web_name, controller_id, var_name, value)
getVar(web_name, controller_id, var_name)
broadcast(controller_id, func, args=(), kwargs=None) -> list[Future]

AxonEvent — events ​

python
from axon import AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent

AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent.add_listener("demo:pong", handler)          # listen to events from JS
AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent.add_listener("demo:once", handler, {"once": True})
AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent.remove_listener("demo:pong", handler)
AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent.remove_all_listeners("demo:pong")

AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent.dispatch_event("demo:pong", 1, 2)           # dispatch inside Python only
AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent.dispatch_js_event("MainView", "demo:event", ["hello"])   # send to the page
AxonEvent  ·  add_listener / dispatch_event / dispatch_js_event / dispatch_js_event_batch / off / on …AxonEvent.dispatch_js_event_batch("demo:event", ["hello"], web_names="*")  # send to every window

Listeners run on a worker thread; an exception is only printed and does not affect the other listeners.

AxonStore — cross-process key/value ​

python
from axon import class AxonStore(id: str, *web_names, auto_create: bool = True)AxonStore

store = class AxonStore(id: str, *web_names, auto_create: bool = True)AxonStore("docs-store", "MainView")   # the name must match the other side
store.set("user", "travis")                    # write and sync to the page
store.get("user")                              # read the local cache
store.prop("theme").set("dark")
store.prop("theme").value
store.release()
MemberMeaning
AxonStore(id, *web_names, auto_create=True)same name reuses the store; web_names are the windows it serves
get(name) / prop(name)read a key (local cache)
set(name, value)write and push to every associated window
setFromPeer(name, value)apply a JS write (framework internal)
AxonStore.sharedprocess-wide shared store
release()unregister

AxonMagicGUI — back to the Qt main thread ​

python
from PySide6.QtWidgets import class QApplicationQApplication
from axon import class AxonMagicGUIAxonMagicGUI

app = class QApplicationQApplication(sys.argv)
class AxonMagicGUIAxonMagicGUI()                        # create it once

def def on_main() -> stron_main() -> str:
    return "now on the Qt main thread"

result = class AxonMagicGUIAxonMagicGUI.run(def on_main() -> stron_main).result(5)

Calling run() before initialisation raises RuntimeError: init AxonMagicGUI first.

Exceptions ​

ExceptionWhen
RuntimeError: web 'X' not foundthe window name does not exist (not created yet, or destroyed)
JSRuntimeErrora JS method threw; the message carries the original error
TimeoutError (from Future.result)waiting for the result timed out

Self-check ​

The repository ships a real-WebEngine assertion suite (37 cases covering both channels, the store, events and the call sugar):

core-py/.venv/bin/python core-py/tests/run_web_tests.py

Errors ​

ClasscodeWhen
AxonTimeoutErrorTIMEOUTno reply from JS (also extends the builtin TimeoutError)
AxonNotConnectedErrorNOT_CONNECTEDthe target window does not exist / was closed
AxonChannelLostErrorCHANNEL_LOSTthe channel dropped mid-flight (page unloaded / renderer crashed)
JSRuntimeErrorJS_RUNTIMEJS raised; the message is carried over
AxonErrorAXONbase class of the three
python
from axon import class Axon(web_name: str)Axon, class AxonTimeoutError
等不到对端回包。
AxonTimeoutError
, class JSRuntimeError
JS 侧抛出、被转成 Python 异常。
JSRuntimeError
try: class Axon(web_name: str)Axon("MainView").DocsJS.mirror({"a": 1}).result(5) except class AxonTimeoutError
等不到对端回包。
AxonTimeoutError
:
print("JS did not answer in 5s") except class JSRuntimeError
JS 侧抛出、被转成 Python 异常。
JSRuntimeError
as exc:
print("JS raised:", exc)