Skip to content

调用 Python 方法 ​

JS → PY

网页里的一个 await Axon.Xxx.方法名(...),会真的调用 Python 里同名的方法,返回值再回到 JS。

Python 侧:先写方法 ​

方法就是普通方法,写在 @AxonController 装饰的类里。类名就是 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") # 注册给窗口 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"阻塞了 {ms}ms" def fail(self, reason: str = "demo") -> None: raise ValueError(f"Python 主动抛出的错误: {reason}")

同步方法跑在线程池里,async def 方法跑在独立的 asyncio 事件循环里,两者都不会卡住界面。

两个名字别搞混

  • 窗口名:@AxonController("MainView") 的第一个参数,要和 AxonGUI("MainView", ...) 一致,决定这个控制器在哪个窗口里可用。不写则对所有窗口生效。
  • 控制器名:默认等于类名(这里就是 DemoController),JS 侧 Axon.DemoController.xxx 用的就是它。想改名写 @AxonController("MainView", id="calc"),JS 侧就变成 Axon.calc.xxx。

JS 侧:三种写法 ​

同样的三个方法,取决于你要不要关键字参数和超时:

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 侧语法糖。

ts
await 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); // 5
js
// [位置参数数组, 关键字参数, 超时毫秒]
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 侧语法糖。

ts
await 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" } // 只给超时也要把关键字参数占位成 {} 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 侧语法糖。

ts
await 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 侧语法糖。

ts
await 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"

判断规则:第一个参数是数组、后面还跟着参数才是打包写法([args], kwargs?, timeout?);只传一个数组时它就是一个普通的数组参数。

下面三个可以直接点的示例分别对应这三种写法(在 Axon 客户端里打开本页时出现):

超时 ​

第三个参数是超时毫秒数。超时后 JS 侧立刻收到 Timeout Error,但 Python 里那次调用仍在继续跑,不会被打断。

app.js
js
// Python 要阻塞 1500ms,这里只等 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 侧语法糖。

ts
await 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[]): void

The 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.

MDN Reference

error
(var err: unknownerr.message); // Timeout Error, py not return in 300ms
}

Python 抛异常 ​

Python 的异常会变成 JS 的 rejected promise,try/catch 就能接住。

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 侧语法糖。

ts
await 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[]): void

The 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.

MDN Reference

error
(var err: unknownerr.message); // Python 主动抛出的错误: manual
}

悬停看类型 ​

AxonCall.call<T>() 的 T 决定 await 之后的类型;载荷里的 controller_id / func / args 也都有类型。

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): string

Returns a string representing a number in fixed-point notation.

@paramfractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
toFixed
(1);
}

要点 ​

  • 一定要 await:不 await 拿到的是 Promise,不是返回值。
  • 方法名就是 Python 的方法名,控制器名是类名(或装饰器里显式写的 id)。
  • 参数走 JSON:能传数字、字符串、列表、字典;传不了文件句柄、类实例、lambda。
  • 同步方法别写太久:它占的是线程池(默认 CPU+4 条),阻塞太久会挤掉别的调用;长任务用 async def。
  • 超时不等于取消:JS 那边报错了,Python 那边的活儿还在跑。