__init__.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. r"""
  2. .. autofunction:: run_async
  3. .. autofunction:: run_asyncio_coroutine
  4. .. autofunction:: register_thread
  5. .. autoclass:: pywebio.session.coroutinebased.TaskHandle
  6. :members:
  7. """
  8. import threading
  9. from functools import wraps
  10. from .base import AbstractSession
  11. from .coroutinebased import CoroutineBasedSession
  12. from .threadbased import ThreadBasedSession, ScriptModeSession
  13. from ..exceptions import SessionNotFoundException
  14. from ..utils import iscoroutinefunction, isgeneratorfunction
  15. # 当前进程中正在使用的会话实现的列表
  16. _active_session_cls = []
  17. __all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread']
  18. def register_session_implement_for_target(target_func):
  19. """根据target_func函数类型注册会话实现,并返回会话实现"""
  20. if iscoroutinefunction(target_func) or isgeneratorfunction(target_func):
  21. cls = CoroutineBasedSession
  22. else:
  23. cls = ThreadBasedSession
  24. if cls not in _active_session_cls:
  25. _active_session_cls.append(cls)
  26. return cls
  27. def get_session_implement():
  28. """获取当前会话实现。仅供内部实现使用。应在会话上下文中调用"""
  29. if not _active_session_cls:
  30. _active_session_cls.append(ScriptModeSession)
  31. _start_script_mode_server()
  32. # 当前正在使用的会话实现只有一个
  33. if len(_active_session_cls) == 1:
  34. return _active_session_cls[0]
  35. # 当前有多个正在使用的会话实现
  36. for cls in _active_session_cls:
  37. try:
  38. cls.get_current_session()
  39. return cls
  40. except SessionNotFoundException:
  41. pass
  42. raise SessionNotFoundException
  43. def _start_script_mode_server():
  44. from ..platform.tornado import start_server_in_current_thread_session
  45. start_server_in_current_thread_session()
  46. def get_current_session() -> "AbstractSession":
  47. return get_session_implement().get_current_session()
  48. def get_current_task_id():
  49. return get_session_implement().get_current_task_id()
  50. def check_session_impl(session_type):
  51. def decorator(func):
  52. @wraps(func)
  53. def inner(*args, **kwargs):
  54. curr_impl = get_session_implement()
  55. # Check if 'now_impl' is a derived from session_type or is the same class
  56. if not issubclass(curr_impl, session_type):
  57. func_name = getattr(func, '__name__', str(func))
  58. require = getattr(session_type, '__name__', str(session_type))
  59. curr = getattr(curr_impl, '__name__', str(curr_impl))
  60. raise RuntimeError("Only can invoke `{func_name:s}` in {require:s} context."
  61. " You are now in {curr:s} context".format(func_name=func_name, require=require,
  62. curr=curr))
  63. return func(*args, **kwargs)
  64. return inner
  65. return decorator
  66. @check_session_impl(CoroutineBasedSession)
  67. def run_async(coro_obj):
  68. """异步运行协程对象。协程中依然可以调用 PyWebIO 交互函数。 仅能在基于协程的会话上下文中调用
  69. :param coro_obj: 协程对象
  70. :return: An instance of `TaskHandle <pywebio.session.coroutinebased.TaskHandle>` is returned, which can be used later to close the task.
  71. """
  72. return get_current_session().run_async(coro_obj)
  73. @check_session_impl(CoroutineBasedSession)
  74. async def run_asyncio_coroutine(coro_obj):
  75. """若会话线程和运行事件的线程不是同一个线程,需要用 run_asyncio_coroutine 来运行asyncio中的协程。 仅能在基于协程的会话上下文中调用
  76. :param coro_obj: 协程对象
  77. """
  78. return await get_current_session().run_asyncio_coroutine(coro_obj)
  79. @check_session_impl(ThreadBasedSession)
  80. def register_thread(thread: threading.Thread):
  81. """注册线程,以便在线程内调用 PyWebIO 交互函数。仅能在基于线程的会话上下文中调用
  82. :param threading.Thread thread: 线程对象
  83. """
  84. return get_current_session().register_thread(thread)