__init__.py 3.6 KB

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