__init__.py 4.3 KB

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