__init__.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 asyncio
  9. import inspect
  10. import threading
  11. from functools import wraps
  12. from .base import AbstractSession
  13. from .coroutinebased import CoroutineBasedSession
  14. from .threadbased import ThreadBasedSession, ScriptModeSession
  15. from ..exceptions import SessionNotFoundException
  16. _session_type = ThreadBasedSession
  17. __all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread']
  18. def set_session_implement_for_target(target_func):
  19. """根据target_func函数类型设置会话实现"""
  20. global _session_type
  21. if asyncio.iscoroutinefunction(target_func) or inspect.isgeneratorfunction(target_func):
  22. _session_type = CoroutineBasedSession
  23. else:
  24. _session_type = ThreadBasedSession
  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.tornado 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)