__init__.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import threading
  2. from functools import wraps
  3. from .base import AbstractSession
  4. from .coroutinebased import CoroutineBasedSession
  5. from .threadbased import ThreadBasedSession, ScriptModeSession
  6. from ..exceptions import SessionNotFoundException
  7. THREAD_BASED = 'ThreadBased'
  8. COROUTINE_BASED = 'CoroutineBased'
  9. _session_type = ThreadBasedSession
  10. __all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread', 'THREAD_BASED', 'COROUTINE_BASED']
  11. _server_started = False
  12. def mark_server_started(session_type_name=None):
  13. """标记服务端已经启动. 仅用于PyWebIO内部使用"""
  14. global _server_started
  15. _server_started = True
  16. if session_type_name is not None:
  17. _set_session_implement(session_type_name)
  18. def _set_session_implement(session_type_name):
  19. """设置会话实现类. 仅用于PyWebIO内部使用"""
  20. global _session_type
  21. sessions = {THREAD_BASED: ThreadBasedSession, COROUTINE_BASED: CoroutineBasedSession}
  22. assert session_type_name in sessions, ValueError('No "%s" Session type ' % session_type_name)
  23. _session_type = sessions[session_type_name]
  24. def get_session_implement():
  25. global _session_type
  26. return _session_type
  27. def _start_script_mode_server():
  28. global _session_type
  29. from ..platform import start_server_in_current_thread_session
  30. _session_type = ScriptModeSession
  31. start_server_in_current_thread_session()
  32. def get_current_session() -> "AbstractSession":
  33. try:
  34. return _session_type.get_current_session()
  35. except SessionNotFoundException:
  36. if _server_started:
  37. raise
  38. # 没有显式启动backend server时,在当前线程上下文作为session启动backend server
  39. _start_script_mode_server()
  40. return _session_type.get_current_session()
  41. def get_current_task_id():
  42. try:
  43. return _session_type.get_current_task_id()
  44. except RuntimeError:
  45. if _server_started:
  46. raise
  47. # 没有显式启动backend server时,在当前线程上下文作为session启动backend server
  48. _start_script_mode_server()
  49. return _session_type.get_current_task_id()
  50. def check_session_impl(session_type):
  51. def decorator(func):
  52. @wraps(func)
  53. def inner(*args, **kwargs):
  54. now_impl = get_session_implement()
  55. if not issubclass(now_impl,
  56. session_type): # Check if 'now_impl' is a derived from session_type or is the same class
  57. func_name = getattr(func, '__name__', str(func))
  58. require = getattr(session_type, '__name__', str(session_type))
  59. now = getattr(now_impl, '__name__', str(now_impl))
  60. raise RuntimeError("Only can invoke `{func_name:s}` in {require:s} context."
  61. " You are now in {now:s} context".format(func_name=func_name, require=require,
  62. now=now))
  63. return func(*args, **kwargs)
  64. return inner
  65. return decorator
  66. @check_session_impl(CoroutineBasedSession)
  67. def run_async(coro_obj):
  68. """异步运行协程对象。协程中依然可以调用 PyWebIO 交互函数。 仅能在 CoroutineBasedSession 会话上下文中调用
  69. :param coro_obj: 协程对象
  70. """
  71. get_current_session().run_async(coro_obj)
  72. @check_session_impl(CoroutineBasedSession)
  73. async def run_asyncio_coroutine(coro_obj):
  74. """若会话线程和运行事件的线程不是同一个线程,需要用 run_asyncio_coroutine 来运行asyncio中的协程
  75. :param coro_obj: 协程对象
  76. """
  77. return await get_current_session().run_asyncio_coroutine(coro_obj)
  78. @check_session_impl(ThreadBasedSession)
  79. def register_thread(thread: threading.Thread, as_daemon=True):
  80. """注册线程,以便在线程内调用 PyWebIO 交互函数。仅能在 ThreadBasedSession 会话上下文中调用
  81. :param threading.Thread thread: 线程对象
  82. """
  83. return get_current_session().register_thread(thread, as_daemon=as_daemon)