Files
gobridge/example/worker.py

76 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "python"))
from gobridge import expose, run
from typing import Iterator
@expose
def add(a: int, b: int) -> int:
return a + b
@expose
def range_gen(start: int, stop: int) -> Iterator[int]:
"""流式输出:对应 Go 侧 Invoke[chan int]"""
for i in range(start, stop):
yield i
@expose
def sum_stream(numbers: Iterator[int]) -> int:
"""流式输入:对应 Go 侧传入 chan int 参数"""
return sum(numbers)
@expose
def double_stream(numbers: Iterator[int]) -> Iterator[int]:
"""双向流输入每个数yield 其平方,对应 Go 侧 Invoke[chan int](c, ctx, "double_stream", inputChan)"""
for n in numbers:
yield n * n
# ── structdict类型 ──────────────────────────────────────────────────────
@expose
def get_user(uid: int) -> dict:
"""普通调用:返回一个 structGo 对应 User"""
return {"id": uid, "name": f"user_{uid}", "score": uid * 1.5}
@expose
def total_score(users: list) -> float:
"""slice 输入:接收 []User返回总分"""
return sum(u["score"] for u in users)
@expose
def enrich_users(users: list) -> list:
"""slice 输入输出:为每个 user 追加 level 字段"""
result = []
for u in users:
u = dict(u)
u["level"] = "gold" if u["score"] >= 10 else "silver"
result.append(u)
return result
# ── struct/slice 流式组合 ────────────────────────────────────────────────────
@expose
def gen_users(count: int) -> Iterator[dict]:
"""流式输出 structyield 多个 User对应 Go 侧 Invoke[chan User]"""
for i in range(1, count + 1):
yield {"id": i, "name": f"user_{i}", "score": float(i * 3)}
@expose
def process_users(users: Iterator[dict]) -> Iterator[dict]:
"""双向流 struct输入流式 Useryield 处理后的 User"""
for u in users:
yield {"id": u["id"], "name": u["name"].upper(), "score": u["score"] * 2}
run()