English
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()| Argument | Meaning |
|---|---|
web_name | window name, unique in the process; controllers and Axon("...") use it to find the window |
url | page 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 / attribute | Meaning |
|---|---|
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_name | the 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:
- every call to that window that is still waiting for a reply fails immediately with
AxonChannelLostError(CHANNEL_LOST) — previously they hung forever unless you passedtimeout; - the
renderProcessCrashedevent is dispatched on the Python side; - 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)
| Argument | Meaning |
|---|---|
web_name | a string or a list; "*" means every window (including windows created later) |
id | controller name, defaults to the class name; JS calls Axon.<id>.<method> |
shared | when 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 poolasync 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.
| Form | Meaning |
|---|---|
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 = v | write 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 windowSignatures:
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 windowListeners 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()| Member | Meaning |
|---|---|
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.shared | process-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
| Exception | When |
|---|---|
RuntimeError: web 'X' not found | the window name does not exist (not created yet, or destroyed) |
JSRuntimeError | a 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.pyErrors
| Class | code | When |
|---|---|---|
AxonTimeoutError | TIMEOUT | no reply from JS (also extends the builtin TimeoutError) |
AxonNotConnectedError | NOT_CONNECTED | the target window does not exist / was closed |
AxonChannelLostError | CHANNEL_LOST | the channel dropped mid-flight (page unloaded / renderer crashed) |
JSRuntimeError | JS_RUNTIME | JS raised; the message is carried over |
AxonError | AXON | base 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)