__init__.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. r"""
  2. .. autofunction:: run_async
  3. .. autofunction:: run_asyncio_coroutine
  4. .. autofunction:: register_thread
  5. .. autofunction:: defer_call
  6. .. autofunction:: hold
  7. .. autoclass:: pywebio.session.coroutinebased.TaskHandle
  8. :members:
  9. """
  10. import threading
  11. from functools import wraps
  12. from .base import AbstractSession
  13. from .coroutinebased import CoroutineBasedSession
  14. from .threadbased import ThreadBasedSession, ScriptModeSession
  15. from ..exceptions import SessionNotFoundException
  16. from ..utils import iscoroutinefunction, isgeneratorfunction, run_as_function, to_coroutine
  17. # 当前进程中正在使用的会话实现的列表
  18. _active_session_cls = []
  19. __all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread', 'hold', 'defer_call']
  20. def register_session_implement_for_target(target_func):
  21. """根据target_func函数类型注册会话实现,并返回会话实现"""
  22. if iscoroutinefunction(target_func) or isgeneratorfunction(target_func):
  23. cls = CoroutineBasedSession
  24. else:
  25. cls = ThreadBasedSession
  26. if cls not in _active_session_cls:
  27. _active_session_cls.append(cls)
  28. return cls
  29. def get_session_implement():
  30. """获取当前会话实现。仅供内部实现使用。应在会话上下文中调用"""
  31. if not _active_session_cls:
  32. _active_session_cls.append(ScriptModeSession)
  33. _start_script_mode_server()
  34. # 当前正在使用的会话实现只有一个
  35. if len(_active_session_cls) == 1:
  36. return _active_session_cls[0]
  37. # 当前有多个正在使用的会话实现
  38. for cls in _active_session_cls:
  39. try:
  40. cls.get_current_session()
  41. return cls
  42. except SessionNotFoundException:
  43. pass
  44. raise SessionNotFoundException
  45. def _start_script_mode_server():
  46. from ..platform.tornado import start_server_in_current_thread_session
  47. start_server_in_current_thread_session()
  48. def get_current_session() -> "AbstractSession":
  49. return get_session_implement().get_current_session()
  50. def get_current_task_id():
  51. return get_session_implement().get_current_task_id()
  52. def check_session_impl(session_type):
  53. def decorator(func):
  54. """装饰器:在函数调用前检查当前会话实现是否满足要求"""
  55. @wraps(func)
  56. def inner(*args, **kwargs):
  57. curr_impl = get_session_implement()
  58. # Check if 'now_impl' is a derived from session_type or is the same class
  59. if not issubclass(curr_impl, session_type):
  60. func_name = getattr(func, '__name__', str(func))
  61. require = getattr(session_type, '__name__', str(session_type))
  62. curr = getattr(curr_impl, '__name__', str(curr_impl))
  63. raise RuntimeError("Only can invoke `{func_name:s}` in {require:s} context."
  64. " You are now in {curr:s} context".format(func_name=func_name, require=require,
  65. curr=curr))
  66. return func(*args, **kwargs)
  67. return inner
  68. return decorator
  69. def chose_impl(gen_func):
  70. """根据当前会话实现来将 gen_func 转化为协程对象或直接以函数运行"""
  71. @wraps(gen_func)
  72. def inner(*args, **kwargs):
  73. gen = gen_func(*args, **kwargs)
  74. if get_session_implement() == CoroutineBasedSession:
  75. return to_coroutine(gen)
  76. else:
  77. return run_as_function(gen)
  78. return inner
  79. @chose_impl
  80. def next_client_event():
  81. res = yield get_current_session().next_client_event()
  82. return res
  83. @chose_impl
  84. def hold():
  85. """保持会话,直到用户关闭浏览器,
  86. 此时函数抛出 `SessionClosedException <pywebio.exceptions.SessionClosedException>` 异常。
  87. 注意⚠️:在 :ref:`基于协程 <coroutine_based_session>` 的会话上下文中,需要使用 ``await hold()`` 语法来进行调用。
  88. """
  89. while True:
  90. yield next_client_event()
  91. @check_session_impl(CoroutineBasedSession)
  92. def run_async(coro_obj):
  93. """异步运行协程对象。协程中依然可以调用 PyWebIO 交互函数。 仅能在 :ref:`基于协程 <coroutine_based_session>` 的会话上下文中调用
  94. :param coro_obj: 协程对象
  95. :return: An instance of `TaskHandle <pywebio.session.coroutinebased.TaskHandle>` is returned, which can be used later to close the task.
  96. """
  97. return get_current_session().run_async(coro_obj)
  98. @check_session_impl(CoroutineBasedSession)
  99. async def run_asyncio_coroutine(coro_obj):
  100. """若会话线程和运行事件的线程不是同一个线程,需要用 run_asyncio_coroutine 来运行asyncio中的协程。 仅能在 :ref:`基于协程 <coroutine_based_session>` 的会话上下文中调用。
  101. :param coro_obj: 协程对象
  102. """
  103. return await get_current_session().run_asyncio_coroutine(coro_obj)
  104. @check_session_impl(ThreadBasedSession)
  105. def register_thread(thread: threading.Thread):
  106. """注册线程,以便在线程内调用 PyWebIO 交互函数。仅能在默认的基于线程的会话上下文中调用。
  107. :param threading.Thread thread: 线程对象
  108. """
  109. return get_current_session().register_thread(thread)
  110. def defer_call(func):
  111. """设置会话结束时调用的函数。无论是用户主动关闭会话还是任务结束会话关闭,设置的函数都会被运行。
  112. 可以用于资源清理等工作。
  113. 在会话中可以多次调用 `defer_call()` ,会话结束后将会顺序执行设置的函数。
  114. :param func: 话结束时调用的函数
  115. """
  116. return get_current_session().defer_call(func)