English
Calling Python methods
JS → PY
A single await Axon.Xxx.method(...) in the page really calls the Python method with that name, and the return value travels back to JS.
Python side: write the method first
A method is just an ordinary method on a class decorated with @AxonController. The class name is the controller name used from JS.
controller.py
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") # registers for the window MainView
class class DemoControllerDemoController:
def add(self, a: int, b: int) -> int:
return a + b
def with_kwargs(self, a: int, b: int = 0, label: str = "none") -> dict:
return {"sum": a + b, "label": label}
async def delayed(self, msg: str, ms: int = 300) -> str:
import asyncio
await asyncio.sleep(ms / 1000)
return f"async:{msg}"
def slow(self, ms: int = 1500) -> str:
import time
time.sleep(ms / 1000)
return f"blocked for {ms}ms"
def fail(self, reason: str = "demo") -> None:
raise ValueError(f"raised on purpose in Python: {reason}")Synchronous methods run on a worker pool and async def methods run on a dedicated asyncio event loop; neither blocks the UI.
Two names that are easy to confuse
- Window name: the first argument of
@AxonController("MainView"). It must matchAxonGUI("MainView", ...)and decides which window can reach this controller. Omit it to make the controller available to every window. - Controller name: defaults to the class name (here
DemoController), which is whatAxon.DemoController.xxxrefers to. To rename it, write@AxonController("MainView", id="calc")and useAxon.calc.xxxfrom JS.
JS side: three ways to call
The same three methods, depending on whether you need keyword arguments or a timeout:
js
const const sum: numbersum = await const Axon: {
DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
... 13 more ...;
counter: number;
};
}
Axon 的 JS 侧语法糖。
tsawait Axon.Users.add(1, 2) // 调 Python 方法, 位置参数直接摊开
await Axon.Users.slow([1000], {}, 300) // 需要 kwargs / 超时时用打包写法
await Axon.Users.count // 读 Python 属性 (getVar)
Axon.Users.count = 3 // 写 Python 属性 (setVar, fire-and-forget)
属性读是惰性的: 只有真正 await / .then / .catch / .finally 时才发请求。
取到的 dispatcher 本身是函数, 同时挂了 then/catch/finally,
让 Axon.Users.count 既能当 Promise 用, 又能当方法调用。
Axon.type DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
fail(reason?: string): Promise<null>;
... 12 more ...;
counter: number;
}
DemoController.function add(a: number, b: number): Promise<number>add(2, 3); // 5js
// [positional args, keyword args, timeout in ms]
const const info: Record<string, any>info = await const Axon: {
DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
... 13 more ...;
counter: number;
};
}
Axon 的 JS 侧语法糖。
tsawait Axon.Users.add(1, 2) // 调 Python 方法, 位置参数直接摊开
await Axon.Users.slow([1000], {}, 300) // 需要 kwargs / 超时时用打包写法
await Axon.Users.count // 读 Python 属性 (getVar)
Axon.Users.count = 3 // 写 Python 属性 (setVar, fire-and-forget)
属性读是惰性的: 只有真正 await / .then / .catch / .finally 时才发请求。
取到的 dispatcher 本身是函数, 同时挂了 then/catch/finally,
让 Axon.Users.count 既能当 Promise 用, 又能当方法调用。
Axon.type DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
fail(reason?: string): Promise<null>;
... 12 more ...;
counter: number;
}
DemoController.function with_kwargs(a: number, b?: number, label?: string): Promise<Record<string, any>>with_kwargs([1], { b: numberb: 2, label: stringlabel: "hi" });
// { sum: 3, label: "hi" }
// a timeout with no kwargs still needs the empty {}
await const Axon: {
DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
... 13 more ...;
counter: number;
};
}
Axon 的 JS 侧语法糖。
tsawait Axon.Users.add(1, 2) // 调 Python 方法, 位置参数直接摊开
await Axon.Users.slow([1000], {}, 300) // 需要 kwargs / 超时时用打包写法
await Axon.Users.count // 读 Python 属性 (getVar)
Axon.Users.count = 3 // 写 Python 属性 (setVar, fire-and-forget)
属性读是惰性的: 只有真正 await / .then / .catch / .finally 时才发请求。
取到的 dispatcher 本身是函数, 同时挂了 then/catch/finally,
让 Axon.Users.count 既能当 Promise 用, 又能当方法调用。
Axon.type DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
fail(reason?: string): Promise<null>;
... 12 more ...;
counter: number;
}
DemoController.function slow(ms?: number): Promise<string>slow([1500], {}, 300);js
const const text: stringtext = await const Axon: {
DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
... 13 more ...;
counter: number;
};
}
Axon 的 JS 侧语法糖。
tsawait Axon.Users.add(1, 2) // 调 Python 方法, 位置参数直接摊开
await Axon.Users.slow([1000], {}, 300) // 需要 kwargs / 超时时用打包写法
await Axon.Users.count // 读 Python 属性 (getVar)
Axon.Users.count = 3 // 写 Python 属性 (setVar, fire-and-forget)
属性读是惰性的: 只有真正 await / .then / .catch / .finally 时才发请求。
取到的 dispatcher 本身是函数, 同时挂了 then/catch/finally,
让 Axon.Users.count 既能当 Promise 用, 又能当方法调用。
Axon.type DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
fail(reason?: string): Promise<null>;
... 12 more ...;
counter: number;
}
DemoController.function delayed(msg: string, ms?: number): Promise<string>delayed("hi", 300); // "async:hi"The rule: the first argument is an array and more arguments follow → packed form ([args], kwargs?, timeout?); a lone array is just an ordinary array argument.
The three clickable demos below match the three forms above (they appear when this page is opened in the Axon client):
Timeout
The third value is a timeout in milliseconds. When it fires, JS immediately gets Timeout Error, but the Python call keeps running — it is not cancelled.
app.js
js
// Python blocks for 1500ms, we only wait 300ms
try {
await const Axon: {
DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
... 13 more ...;
counter: number;
};
}
Axon 的 JS 侧语法糖。
tsawait Axon.Users.add(1, 2) // 调 Python 方法, 位置参数直接摊开
await Axon.Users.slow([1000], {}, 300) // 需要 kwargs / 超时时用打包写法
await Axon.Users.count // 读 Python 属性 (getVar)
Axon.Users.count = 3 // 写 Python 属性 (setVar, fire-and-forget)
属性读是惰性的: 只有真正 await / .then / .catch / .finally 时才发请求。
取到的 dispatcher 本身是函数, 同时挂了 then/catch/finally,
让 Axon.Users.count 既能当 Promise 用, 又能当方法调用。
Axon.type DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
fail(reason?: string): Promise<null>;
... 12 more ...;
counter: number;
}
DemoController.function slow(ms?: number): Promise<string>slow([1500], {}, 300);
} catch (var err: unknownerr) {
var console: Consoleconsole.Console.error(...data: any[]): voidThe console.error() static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.
error(var err: unknownerr.message); // Timeout Error, py not return in 300ms
}Python raising an exception
A Python exception becomes a rejected promise on the JS side, so try/catch receives it.
app.js
js
try {
await const Axon: {
DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
... 13 more ...;
counter: number;
};
}
Axon 的 JS 侧语法糖。
tsawait Axon.Users.add(1, 2) // 调 Python 方法, 位置参数直接摊开
await Axon.Users.slow([1000], {}, 300) // 需要 kwargs / 超时时用打包写法
await Axon.Users.count // 读 Python 属性 (getVar)
Axon.Users.count = 3 // 写 Python 属性 (setVar, fire-and-forget)
属性读是惰性的: 只有真正 await / .then / .catch / .finally 时才发请求。
取到的 dispatcher 本身是函数, 同时挂了 then/catch/finally,
让 Axon.Users.count 既能当 Promise 用, 又能当方法调用。
Axon.type DemoController: {
add(a: number, b: number): Promise<number>;
asset_count(): Promise<number>;
blob(size?: number): Promise<string>;
broadcast(text: string): Promise<Array<any>>;
call_js_mirror(payload: any): Promise<any>;
cross_broadcast(text?: string): Promise<Record<string, any>>;
cross_call(text?: string): Promise<any>;
cross_close(): Promise<Array<string>>;
cross_emit(text?: string): Promise<Array<string>>;
cross_open(): Promise<Array<string>>;
delayed(msg: string, ms?: number): Promise<string>;
fail(reason?: string): Promise<null>;
... 12 more ...;
counter: number;
}
DemoController.function fail(reason?: string): Promise<null>fail("manual");
} catch (var err: unknownerr) {
var console: Consoleconsole.Console.error(...data: any[]): voidThe console.error() static method outputs a message to the console at the "error" log level. The message is only displayed to the user if the console is configured to display error output. In most cases, the log level is configured within the console UI. The message may be formatted as an error, with red colors and call stack information.
error(var err: unknownerr.message); // raised on purpose in Python: manual
}Hover to see the types
AxonCall.call<T>() — T decides what await gives you; the payload fields are typed too.
ts
import { const AxonCall: {
init(): Promise<void>;
__call__<K extends SmartPYControllerName, F extends SmartPYControllerPropName<K>, T = unknown>({ controller_id, prop, args, kwargs, timeout, type, }: {
controller_id: K;
prop: F;
args?: any[];
kwargs?: { [key in string]: any; };
timeout?: number;
type: JSCallType;
}): Promise<T>;
call<T = unknown, K extends SmartPYControllerName = SmartPYControllerName, F extends SmartPYControllerPropName<K> = SmartPYControllerPropName<...>>(data: {
controller_id: K;
func: F;
args?: any[];
kwargs?: { [key in string]: any; };
timeout?: number;
}): Promise<T>;
... 5 more ...;
returnReceiver([call_id, state, data]: JSRetData): void;
}
AxonCall } from "axon-gui";
async function function addTwo(): Promise<string>addTwo() {
const const sum: numbersum = await const AxonCall: {
init(): Promise<void>;
__call__<K extends SmartPYControllerName, F extends SmartPYControllerPropName<K>, T = unknown>({ controller_id, prop, args, kwargs, timeout, type, }: {
controller_id: K;
prop: F;
args?: any[];
kwargs?: { [key in string]: any; };
timeout?: number;
type: JSCallType;
}): Promise<T>;
call<T = unknown, K extends SmartPYControllerName = SmartPYControllerName, F extends SmartPYControllerPropName<K> = SmartPYControllerPropName<...>>(data: {
controller_id: K;
func: F;
args?: any[];
kwargs?: { [key in string]: any; };
timeout?: number;
}): Promise<T>;
... 5 more ...;
returnReceiver([call_id, state, data]: JSRetData): void;
}
AxonCall.call<number, SmartPYControllerName, string>(data: {
controller_id: SmartPYControllerName;
func: string;
args?: any[];
kwargs?: { [key in string]: any; };
timeout?: number;
}): Promise<number>
调 Python 控制器的方法;返回类型可以自己指定:await AxonCall.call<number>({...})。
call<number>({ controller_id: SmartPYControllerNamecontroller_id: "DemoController", func: stringfunc: "add", args?: any[] | undefinedargs: [2, 3] });
return const sum: numbersum.Number.toFixed(fractionDigits?: number): stringReturns a string representing a number in fixed-point notation.
toFixed(1);
}Key points
- Always
await: without it you get a Promise, not the return value. - The method name is the Python method name; the controller name is the class name (or the explicit
id=given to the decorator). - Arguments travel as JSON: numbers, strings, lists and dicts are fine; file handles, class instances and lambdas are not.
- Keep synchronous methods short: they occupy the worker pool (CPU+4 threads); long tasks belong in
async def. - A timeout is not a cancellation: JS gives up, Python keeps working.