__init__.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. r"""
  2. .. autofunction:: run_async
  3. .. autofunction:: run_asyncio_coroutine
  4. .. autofunction:: register_thread
  5. """
  6. import asyncio
  7. import inspect
  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. THREAD_BASED = 'ThreadBased'
  15. COROUTINE_BASED = 'CoroutineBased'
  16. SCRIPT_MODE = 'ScriptMode'
  17. _session_type = ThreadBasedSession
  18. __all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread', 'THREAD_BASED', 'COROUTINE_BASED']
  19. def get_session_implement_for_target(target_func):
  20. """根据target_func函数类型获取默认会话实现"""
  21. if asyncio.iscoroutinefunction(target_func) or inspect.isgeneratorfunction(target_func):
  22. return COROUTINE_BASED
  23. return THREAD_BASED
  24. def set_session_implement(session_type_name):
  25. """设置会话实现类. 仅用于PyWebIO内部使用"""
  26. global _session_type
  27. sessions = {THREAD_BASED: ThreadBasedSession, COROUTINE_BASED: CoroutineBasedSession, SCRIPT_MODE: ScriptModeSession}
  28. assert session_type_name in sessions, ValueError('No "%s" Session type ' % session_type_name)
  29. _session_type = sessions[session_type_name]
  30. def get_session_implement():
  31. global _session_type
  32. return _session_type
  33. def _start_script_mode_server():
  34. global _session_type
  35. from ..platform.tornado import start_server_in_current_thread_session
  36. _session_type = ScriptModeSession
  37. start_server_in_current_thread_session()
  38. def get_current_session() -> "AbstractSession":
  39. try:
  40. return _session_type.get_current_session()
  41. except SessionNotFoundException:
  42. # 如果没已经运行的backend server,在当前线程上下文作为session启动backend server
  43. if get_session_implement().active_session_count() == 0:
  44. _start_script_mode_server()
  45. return _session_type.get_current_session()
  46. else:
  47. raise
  48. def get_current_task_id():
  49. try:
  50. return _session_type.get_current_task_id()
  51. except RuntimeError:
  52. # 如果没已经运行的backend server,在当前线程上下文作为session启动backend server
  53. if get_session_implement().active_session_count() == 0:
  54. _start_script_mode_server()
  55. return _session_type.get_current_session()
  56. else:
  57. raise
  58. def check_session_impl(session_type):
  59. def decorator(func):
  60. @wraps(func)
  61. def inner(*args, **kwargs):
  62. now_impl = get_session_implement()
  63. if not issubclass(now_impl,
  64. session_type): # Check if 'now_impl' is a derived from session_type or is the same class
  65. func_name = getattr(func, '__name__', str(func))
  66. require = getattr(session_type, '__name__', str(session_type))
  67. now = getattr(now_impl, '__name__', str(now_impl))
  68. raise RuntimeError("Only can invoke `{func_name:s}` in {require:s} context."
  69. " You are now in {now:s} context".format(func_name=func_name, require=require,
  70. now=now))
  71. return func(*args, **kwargs)
  72. return inner
  73. return decorator
  74. @check_session_impl(CoroutineBasedSession)
  75. def run_async(coro_obj):
  76. """异步运行协程对象。协程中依然可以调用 PyWebIO 交互函数。 仅能在 CoroutineBasedSession 会话上下文中调用
  77. :param coro_obj: 协程对象
  78. :return: An instance of `TaskHandle <pywebio.session.coroutinebased.TaskHandle>` is returned, which can be used later to close the task.
  79. """
  80. return get_current_session().run_async(coro_obj)
  81. @check_session_impl(CoroutineBasedSession)
  82. async def run_asyncio_coroutine(coro_obj):
  83. """若会话线程和运行事件的线程不是同一个线程,需要用 run_asyncio_coroutine 来运行asyncio中的协程
  84. :param coro_obj: 协程对象
  85. """
  86. return await get_current_session().run_asyncio_coroutine(coro_obj)
  87. @check_session_impl(ThreadBasedSession)
  88. def register_thread(thread: threading.Thread):
  89. """注册线程,以便在线程内调用 PyWebIO 交互函数。仅能在 ThreadBasedSession 会话上下文中调用
  90. :param threading.Thread thread: 线程对象
  91. """
  92. return get_current_session().register_thread(thread)