Skip to content

Commit 0b9ace1

Browse files
committed
fix callback have no page context
1 parent 0834386 commit 0b9ace1

File tree

7 files changed

+29
-12
lines changed

7 files changed

+29
-12
lines changed

pywebio/output.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,12 +1867,12 @@ def __call__(self, func):
18671867

18681868
@wraps(func)
18691869
def wrapper(*args, **kwargs):
1870-
with self:
1870+
with page_(): # can't use `with self:`, it will use same object in different calls to same decorated func
18711871
return func(*args, **kwargs)
18721872

18731873
@wraps(func)
18741874
async def coro_wrapper(*args, **kwargs):
1875-
with self:
1875+
with page_():
18761876
return await func(*args, **kwargs)
18771877

18781878
if iscoroutinefunction(func):

pywebio/session/base.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,9 +133,10 @@ def pop_page(self):
133133
pass
134134
return page_id
135135

136-
def push_page(self, page_id):
136+
def push_page(self, page_id, task_id=None):
137137
self.push_scope(ROOT_SCOPE)
138-
task_id = type(self).get_current_task_id()
138+
if task_id is None:
139+
task_id = type(self).get_current_task_id()
139140
self.page_stack[task_id].append(page_id)
140141
self.active_page[task_id].add(page_id)
141142

pywebio/session/coroutinebased.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,7 @@ def register_callback(self, callback, mutex_mode=False):
176176
:param bool mutex_mode: 互斥模式。若为 ``True`` ,则在运行回调函数过程中,无法响应同一组件(callback_id相同)的新点击事件,仅当 ``callback`` 为协程函数时有效
177177
:return str: 回调id.
178178
"""
179+
page_id = self.get_page_id()
179180

180181
async def callback_coro():
181182
while True:
@@ -204,7 +205,7 @@ async def callback_coro():
204205
if mutex_mode:
205206
await coro
206207
else:
207-
self.run_async(coro)
208+
self._run_async(coro, page_id=page_id)
208209

209210
cls = type(self)
210211
callback_task = Task(callback_coro(), cls.get_current_session())
@@ -224,12 +225,17 @@ def run_async(self, coro_obj):
224225
:param coro_obj: 协程对象
225226
:return: An instance of `TaskHandler` is returned, which can be used later to close the task.
226227
"""
228+
return self._run_async(coro_obj)
229+
230+
def _run_async(self, coro_obj, page_id=None):
227231
assert asyncio.iscoroutine(coro_obj), '`run_async()` only accept coroutine object'
232+
if page_id is None:
233+
page_id = self.get_page_id()
228234

229235
self._alive_coro_cnt += 1
230-
231236
task = Task(coro_obj, session=self, on_coro_stop=self._on_task_finish)
232237
self.coros[task.coro_id] = task
238+
self.push_page(page_id, task_id=task.coro_id)
233239
asyncio.get_event_loop().call_soon_threadsafe(task.step)
234240
return task.task_handle()
235241

pywebio/session/threadbased.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ def _dispatch_callback_event(self):
252252
if not callback_info:
253253
logger.error("No callback for callback_id:%s", event['task_id'])
254254
return
255-
callback, mutex = callback_info
255+
callback, mutex, page_id = callback_info
256256

257257
@wraps(callback)
258258
def run(callback):
@@ -270,7 +270,7 @@ def run(callback):
270270
else:
271271
t = threading.Thread(target=run, kwargs=dict(callback=callback),
272272
daemon=True)
273-
self.register_thread(t)
273+
self._register_thread(t, page_id)
274274
t.start()
275275

276276
def register_callback(self, callback, serial_mode=False):
@@ -285,7 +285,7 @@ def register_callback(self, callback, serial_mode=False):
285285

286286
self._activate_callback_env()
287287
callback_id = 'CB-%s-%s' % (get_function_name(callback, 'callback'), random_str(10))
288-
self.callbacks[callback_id] = (callback, serial_mode)
288+
self.callbacks[callback_id] = (callback, serial_mode, self.get_page_id())
289289
return callback_id
290290

291291
def register_thread(self, t: threading.Thread):
@@ -294,10 +294,16 @@ def register_thread(self, t: threading.Thread):
294294
295295
:param threading.Thread thread: 线程对象
296296
"""
297+
return self._register_thread(t)
298+
299+
def _register_thread(self, t: threading.Thread, page_id=None):
300+
if page_id is None:
301+
page_id = self.get_page_id()
297302
self.threads.append(t) # 保存 registered thread,用于主任务线程退出后等待注册线程结束
298303
self.thread2session[id(t)] = self # 用于在线程内获取会话
299304
event_mq = queue.Queue(maxsize=self.event_mq_maxsize) # 线程内的用户事件队列
300305
self.task_mqs[self._get_task_id(t)] = event_mq
306+
self.push_page(page_id, task_id=self._get_task_id(t))
301307

302308
def need_keep_alive(self) -> bool:
303309
# if callback thread is activated, then the session need to keep alive

webiojs/src/handlers/base.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {Command, Session} from "../session";
22
import {DeliverMessage} from "../models/page";
3+
import {PAGE_COMMANDS} from "./page";
34

45

56
export interface CommandHandler {
@@ -36,7 +37,7 @@ export class CommandDispatcher {
3637
}
3738

3839
dispatch_message(msg: Command): boolean {
39-
if (msg.page !== undefined && msg.page) {
40+
if (msg.page !== undefined && msg.page && PAGE_COMMANDS.indexOf(msg.command) == -1) {
4041
DeliverMessage(msg);
4142
} else if (msg.command in this.command2handler) {
4243
this.command2handler[msg.command].handle_message(msg);

webiojs/src/handlers/page.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import {Command} from "../session";
22
import {CommandHandler} from "./base";
33
import {ClosePage, OpenPage} from "../models/page";
44

5+
export const PAGE_COMMANDS = ['open_page', 'close_page']
6+
57
export class PageHandler implements CommandHandler {
6-
accept_command: string[] = ['open_page', 'close_page'];
8+
accept_command: string[] = PAGE_COMMANDS;
79

810
constructor() {
911
}

webiojs/src/models/page.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,9 @@ export function OpenPage(page_id: string, task_id: string) {
6565
}
6666

6767
export function ClosePage(page_id: string) {
68-
if (!(page_id in subpages))
68+
if (!(page_id in subpages)) {
6969
throw `Can't close page, the page (id "${page_id}") is not found`;
70+
}
7071
subpages[page_id].page.close();
7172
delete subpages[page_id];
7273
}

0 commit comments

Comments
 (0)