__init__.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. r"""
  2. .. autofunction:: run_async
  3. .. autofunction:: run_asyncio_coroutine
  4. .. autofunction:: download
  5. .. autofunction:: run_js
  6. .. autofunction:: eval_js
  7. .. autofunction:: register_thread
  8. .. autofunction:: defer_call
  9. .. autofunction:: hold
  10. .. data:: local
  11. The session-local object for current session.
  12. ``local`` is a dictionary that can be accessed through attributes. When accessing a property that does not exist in the data object, it returns ``None`` instead of throwing an exception.
  13. The method of dictionary is not supported in ``local``. It supports the ``in`` operator to determine whether the key exists. You can use ``local._dict`` to get the underlying dictionary data.
  14. :Usage Scenes:
  15. When you need to share some session-independent data with multiple functions, it is more convenient to use session-local objects to save state than to use function parameters.
  16. Here is a example of a session independent counter implementation::
  17. from pywebio.session import local
  18. def add():
  19. local.cnt = (local.cnt or 0) + 1
  20. def show():
  21. put_text(local.cnt or 0)
  22. def main():
  23. put_buttons(['Add counter', 'Show counter'], [add, show])
  24. hold()
  25. The way to pass state through function parameters is::
  26. from functools import partial
  27. def add(cnt):
  28. cnt[0] += 1
  29. def show(cnt):
  30. put_text(cnt[0])
  31. def main():
  32. cnt = [0] # Trick: to pass by reference
  33. put_buttons(['Add counter', 'Show counter'], [partial(add, cnt), partial(show, cnt)])
  34. hold()
  35. Of course, you can also use function closures to achieved the same::
  36. def main():
  37. cnt = 0
  38. def add():
  39. nonlocal cnt
  40. cnt += 1
  41. def show():
  42. put_text(cnt)
  43. put_buttons(['Add counter', 'Show counter'], [add, show])
  44. hold()
  45. :``local`` usage:
  46. ::
  47. local.name = "Wang"
  48. local.age = 22
  49. assert local.foo is None
  50. local[10] = "10"
  51. for key in local:
  52. print(key)
  53. assert 'bar' not in local
  54. assert 'name' in local
  55. print(local._dict)
  56. .. versionadded:: 1.1
  57. .. autofunction:: set_env
  58. .. autofunction:: go_app
  59. .. data:: info
  60. The session information data object, whose attributes are:
  61. * ``user_agent`` : The Object of the user browser information, whose attributes are
  62. * ``is_mobile`` (bool): whether user agent is identified as a mobile phone (iPhone, Android phones, Blackberry, Windows Phone devices etc)
  63. * ``is_tablet`` (bool): whether user agent is identified as a tablet device (iPad, Kindle Fire, Nexus 7 etc)
  64. * ``is_pc`` (bool): whether user agent is identified to be running a traditional "desktop" OS (Windows, OS X, Linux)
  65. * ``is_touch_capable`` (bool): whether user agent has touch capabilities
  66. * ``browser.family`` (str): Browser family. such as 'Mobile Safari'
  67. * ``browser.version`` (tuple): Browser version. such as (5, 1)
  68. * ``browser.version_string`` (str): Browser version string. such as '5.1'
  69. * ``os.family`` (str): User OS family. such as 'iOS'
  70. * ``os.version`` (tuple): User OS version. such as (5, 1)
  71. * ``os.version_string`` (str): User OS version string. such as '5.1'
  72. * ``device.family`` (str): User agent's device family. such as 'iPhone'
  73. * ``device.brand`` (str): Device brand. such as 'Apple'
  74. * ``device.model`` (str): Device model. such as 'iPhone'
  75. * ``user_language`` (str): Language used by the user's operating system. (e.g., ``'zh-CN'``)
  76. * ``server_host`` (str): PyWebIO server host, including domain and port, the port can be omitted when 80.
  77. * ``origin`` (str): Indicate where the user from. Including protocol, host, and port parts. Such as ``'http://localhost:8080'`` .
  78. It may be empty, but it is guaranteed to have a value when the user's page address is not under the server host. (that is, the host, port part are inconsistent with ``server_host``).
  79. * ``user_ip`` (str): User's ip address.
  80. * ``backend`` (str): The current PyWebIO backend server implementation. The possible values are ``'tornado'``, ``'flask'``, ``'django'`` , ``'aiohttp'`` , ``'starlette'``.
  81. * ``protocol`` (str): The communication protocol between PyWebIO server and browser. The possible values are ``'websocket'``, ``'http'``
  82. * ``request`` (object): The request object when creating the current session. Depending on the backend server, the type of ``request`` can be:
  83. * When using Tornado, ``request`` is instance of
  84. `tornado.httputil.HTTPServerRequest <https://www.tornadoweb.org/en/stable/httputil.html#tornado.httputil.HTTPServerRequest>`_
  85. * When using Flask, ``request`` is instance of `flask.Request <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>`_
  86. * When using Django, ``request`` is instance of `django.http.HttpRequest <https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpRequest>`_
  87. * When using aiohttp, ``request`` is instance of `aiohttp.web.BaseRequest <https://docs.aiohttp.org/en/stable/web_reference.html#aiohttp.web.BaseRequest>`_
  88. * When using FastAPI/Starlette, ``request`` is instance of `starlette.websockets.WebSocket <https://www.starlette.io/websockets/>`_
  89. The ``user_agent`` attribute of the session information object is parsed by the user-agents library. See https://github.com/selwin/python-user-agents#usage
  90. .. versionchanged:: 1.2
  91. Added the ``protocol`` attribute.
  92. Example:
  93. .. exportable-codeblock::
  94. :name: get_info
  95. :summary: `session.info` usage
  96. import json
  97. from pywebio.session import info as session_info
  98. put_code(json.dumps({
  99. k: str(getattr(session_info, k))
  100. for k in ['user_agent', 'user_language', 'server_host',
  101. 'origin', 'user_ip', 'backend', 'protocol', 'request']
  102. }, indent=4), 'json')
  103. .. autoclass:: pywebio.session.coroutinebased.TaskHandler
  104. :members:
  105. """
  106. import threading
  107. from base64 import b64encode
  108. from functools import wraps
  109. import user_agents
  110. from .base import Session
  111. from .coroutinebased import CoroutineBasedSession
  112. from .threadbased import ThreadBasedSession, ScriptModeSession
  113. from ..exceptions import SessionNotFoundException, SessionException
  114. from ..utils import iscoroutinefunction, isgeneratorfunction, run_as_function, to_coroutine, ObjectDictProxy, \
  115. ReadOnlyObjectDict
  116. # 当前进程中正在使用的会话实现的列表
  117. # List of session implementations currently in use
  118. _active_session_cls = []
  119. __all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread', 'hold', 'defer_call', 'data', 'get_info',
  120. 'run_js', 'eval_js', 'download', 'set_env', 'go_app', 'local', 'info']
  121. def register_session_implement(cls):
  122. if cls not in _active_session_cls:
  123. _active_session_cls.append(cls)
  124. return cls
  125. def register_session_implement_for_target(target_func):
  126. """根据target_func函数类型注册会话实现,并返回会话实现
  127. Register the session implementation according to the target_func function type, and return the session implementation"""
  128. if iscoroutinefunction(target_func) or isgeneratorfunction(target_func):
  129. cls = CoroutineBasedSession
  130. else:
  131. cls = ThreadBasedSession
  132. if ScriptModeSession in _active_session_cls:
  133. raise RuntimeError("Already in script mode, can't start server")
  134. if cls not in _active_session_cls:
  135. _active_session_cls.append(cls)
  136. return cls
  137. def get_session_implement():
  138. """获取当前会话实现。仅供内部实现使用。应在会话上下文中调用
  139. Get the current session implementation. For internal implementation use only. Should be called in session context"""
  140. if not _active_session_cls:
  141. _active_session_cls.append(ScriptModeSession)
  142. _start_script_mode_server()
  143. # 当前正在使用的会话实现只有一个
  144. # There is only one session implementation currently in use
  145. if len(_active_session_cls) == 1:
  146. return _active_session_cls[0]
  147. # 当前有多个正在使用的会话实现
  148. # There are currently multiple session implementations in use
  149. for cls in _active_session_cls:
  150. try:
  151. cls.get_current_session()
  152. return cls
  153. except SessionNotFoundException:
  154. pass
  155. raise SessionNotFoundException
  156. def _start_script_mode_server():
  157. from ..platform.tornado import start_server_in_current_thread_session
  158. start_server_in_current_thread_session()
  159. def get_current_session() -> "Session":
  160. return get_session_implement().get_current_session()
  161. def get_current_task_id():
  162. return get_session_implement().get_current_task_id()
  163. def check_session_impl(session_type):
  164. def decorator(func):
  165. """装饰器:在函数调用前检查当前会话实现是否满足要求
  166. Decorator: Check whether the current session implementation meets the requirements before the function call"""
  167. @wraps(func)
  168. def inner(*args, **kwargs):
  169. curr_impl = get_session_implement()
  170. # Check if 'now_impl' is a derived from session_type or is the same class
  171. if not issubclass(curr_impl, session_type):
  172. func_name = getattr(func, '__name__', str(func))
  173. require = getattr(session_type, '__name__', str(session_type))
  174. curr = getattr(curr_impl, '__name__', str(curr_impl))
  175. raise RuntimeError("Only can invoke `{func_name:s}` in {require:s} context."
  176. " You are now in {curr:s} context".format(func_name=func_name, require=require,
  177. curr=curr))
  178. return func(*args, **kwargs)
  179. return inner
  180. return decorator
  181. def chose_impl(gen_func):
  182. """
  183. 装饰器,使用chose_impl对gen_func进行装饰后,gen_func() 调用将根据当前会话实现来确定是 返回协程对象 还是 直接运行函数体
  184. Decorator, after using `choose_impl` to decorate `gen_func`, according to the current session implementation, the `gen_func()` call will either return the coroutine object or directly run the function body
  185. """
  186. @wraps(gen_func)
  187. def inner(*args, **kwargs):
  188. gen = gen_func(*args, **kwargs)
  189. if get_session_implement() == CoroutineBasedSession:
  190. return to_coroutine(gen)
  191. else:
  192. return run_as_function(gen)
  193. return inner
  194. @chose_impl
  195. def next_client_event():
  196. res = yield get_current_session().next_client_event()
  197. return res
  198. @chose_impl
  199. def hold():
  200. """Keep the session alive until the browser page is closed by user.
  201. .. note::
  202. After the PyWebIO session closed, the functions that need communicate with the PyWebIO server (such as the event callback of `put_buttons()` and download link of `put_file()`) will not work. You can call the ``hold()`` function at the end of the task function to hold the session, so that the event callback and download link will always be available before the browser page is closed by user.
  203. Note: When using :ref:`coroutine-based session <coroutine_based_session>`, you need to use the ``await hold()`` syntax to call the function.
  204. """
  205. while True:
  206. try:
  207. yield next_client_event()
  208. except SessionException:
  209. return
  210. def download(name, content):
  211. """Send file to user, and the user browser will download the file to the local
  212. :param str name: File name when downloading
  213. :param content: File content. It is a bytes-like object
  214. Example:
  215. .. exportable-codeblock::
  216. :name: download
  217. :summary: `download()` usage
  218. put_buttons(['Click to download'],
  219. [lambda: download('hello-world.txt', b'hello world!')])
  220. """
  221. from ..io_ctrl import send_msg
  222. content = b64encode(content).decode('ascii')
  223. send_msg('download', spec=dict(name=name, content=content))
  224. def run_js(code_, **args):
  225. """Execute JavaScript code in user browser.
  226. The code is run in the browser's JS global scope.
  227. :param str code_: JavaScript code
  228. :param args: Local variables passed to js code. Variables need to be JSON-serializable.
  229. Example::
  230. run_js('console.log(a + b)', a=1, b=2)
  231. """
  232. from ..io_ctrl import send_msg
  233. send_msg('run_script', spec=dict(code=code_, args=args))
  234. @chose_impl
  235. def eval_js(expression_, **args):
  236. """Execute JavaScript expression in the user's browser and get the value of the expression
  237. :param str expression_: JavaScript expression. The value of the expression need to be JSON-serializable.
  238. If the value of the expression is a `promise <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>`_,
  239. ``eval_js()`` will wait for the promise to resolve and return the value of it. When the promise is rejected, `None` is returned.
  240. :param args: Local variables passed to js code. Variables need to be JSON-serializable.
  241. :return: The value of the expression.
  242. Note: When using :ref:`coroutine-based session <coroutine_based_session>`, you need to use the ``await eval_js(expression)`` syntax to call the function.
  243. Example:
  244. .. exportable-codeblock::
  245. :name: eval_js
  246. :summary: `eval_js()` usage
  247. current_url = eval_js("window.location.href")
  248. put_text(current_url) # ..demo-only
  249. ## ----
  250. function_res = eval_js('''(function(){
  251. var a = 1;
  252. a += b;
  253. return a;
  254. })()''', b=100)
  255. put_text(function_res) # ..demo-only
  256. ## ----
  257. promise_res = eval_js('''new Promise(resolve => {
  258. setTimeout(() => {
  259. resolve('Returned inside callback.');
  260. }, 2000);
  261. });''')
  262. put_text(promise_res) # ..demo-only
  263. .. versionchanged:: 1.3
  264. The JS expression support return promise.
  265. """
  266. from ..io_ctrl import send_msg
  267. send_msg('run_script', spec=dict(code=expression_, args=args, eval=True))
  268. res = yield next_client_event()
  269. assert res['event'] == 'js_yield', "Internal Error, please report this bug on " \
  270. "https://github.com/wang0618/PyWebIO/issues"
  271. return res['data']
  272. @check_session_impl(CoroutineBasedSession)
  273. def run_async(coro_obj):
  274. """Run the coroutine object asynchronously. PyWebIO interactive functions are also available in the coroutine.
  275. ``run_async()`` can only be used in :ref:`coroutine-based session <coroutine_based_session>`.
  276. :param coro_obj: Coroutine object
  277. :return: `TaskHandle <pywebio.session.coroutinebased.TaskHandle>` instance, which can be used to query the running status of the coroutine or close the coroutine.
  278. See also: :ref:`Concurrency in coroutine-based sessions <coroutine_based_concurrency>`
  279. """
  280. return get_current_session().run_async(coro_obj)
  281. @check_session_impl(CoroutineBasedSession)
  282. async def run_asyncio_coroutine(coro_obj):
  283. """
  284. If the thread running sessions are not the same as the thread running the asyncio event loop, you need to wrap ``run_asyncio_coroutine()`` to run the coroutine in asyncio.
  285. Can only be used in :ref:`coroutine-based session <coroutine_based_session>`.
  286. :param coro_obj: Coroutine object in `asyncio`
  287. Example::
  288. async def app():
  289. put_text('hello')
  290. await run_asyncio_coroutine(asyncio.sleep(1))
  291. put_text('world')
  292. pywebio.platform.flask.start_server(app)
  293. """
  294. return await get_current_session().run_asyncio_coroutine(coro_obj)
  295. @check_session_impl(ThreadBasedSession)
  296. def register_thread(thread: threading.Thread):
  297. """Register the thread so that PyWebIO interactive functions are available in the thread.
  298. Can only be used in the thread-based session.
  299. See :ref:`Concurrent in Server mode <thread_in_server_mode>`
  300. :param threading.Thread thread: Thread object
  301. """
  302. return get_current_session().register_thread(thread)
  303. def defer_call(func):
  304. """Set the function to be called when the session closes.
  305. Whether it is because the user closes the page or the task finishes to cause session closed, the function set by ``defer_call(func)`` will be executed. Can be used for resource cleaning.
  306. You can call ``defer_call(func)`` multiple times in the session, and the set functions will be executed sequentially after the session closes.
  307. ``defer_call()`` can also be used as decorator::
  308. @defer_call
  309. def cleanup():
  310. pass
  311. .. attention:: PyWebIO interactive functions cannot be called inside the deferred functions.
  312. """
  313. get_current_session().defer_call(func)
  314. return func
  315. # session-local data object
  316. local = ObjectDictProxy(lambda: get_current_session().save)
  317. def data():
  318. """Get the session-local object of current session.
  319. .. deprecated:: 1.1
  320. Use `local <pywebio.session.local>` instead.
  321. """
  322. global local
  323. import warnings
  324. warnings.warn("`pywebio.session.data()` is deprecated since v1.1 and will remove in the future version, "
  325. "use `pywebio.session.local` instead", DeprecationWarning, stacklevel=2)
  326. return local
  327. def set_env(**env_info):
  328. """Config the environment of current session.
  329. Available configuration are:
  330. * ``title`` (str): Title of current page.
  331. * ``output_animation`` (bool): Whether to enable output animation, enabled by default
  332. * ``auto_scroll_bottom`` (bool): Whether to automatically scroll the page to the bottom after output content, it is closed by default. Note that after enabled, only outputting to ROOT scope can trigger automatic scrolling.
  333. * ``http_pull_interval`` (int): The period of HTTP polling messages (in milliseconds, default 1000ms), only available in sessions based on HTTP connection.
  334. * ``input_panel_fixed`` (bool): Whether to make input panel fixed at bottom, enabled by default
  335. * ``input_panel_min_height`` (int): The minimum height of input panel (in pixel, default 300px), it should be larger than 75px. Available only when ``input_panel_fixed=True``
  336. * ``input_panel_init_height`` (int): The initial height of input panel (in pixel, default 300px), it should be larger than 175px. Available only when ``input_panel_fixed=True``
  337. * ``input_auto_focus`` (bool): Whether to focus on input automatically after showing input panel, default is ``True``
  338. Example::
  339. set_env(title='Awesome PyWebIO!!', output_animation=False)
  340. """
  341. from ..io_ctrl import send_msg
  342. assert all(k in ('title', 'output_animation', 'auto_scroll_bottom', 'http_pull_interval',
  343. 'input_panel_min_height', 'input_panel_init_height', 'input_panel_fixed', 'input_auto_focus')
  344. for k in env_info.keys())
  345. send_msg('set_env', spec=env_info)
  346. def go_app(name, new_window=True):
  347. """Jump to another task of a same PyWebIO application. Only available in PyWebIO Server mode
  348. :param str name: Target PyWebIO task name.
  349. :param bool new_window: Whether to open in a new window, the default is `True`
  350. See also: :ref:`Server mode <server_and_script_mode>`
  351. """
  352. run_js('javascript:WebIO.openApp(app, new_window)', app=name, new_window=new_window)
  353. # session info data object
  354. info = ReadOnlyObjectDict(lambda: get_current_session().internal_save['info']) # type: _SessionInfoType
  355. class _SessionInfoType:
  356. user_agent = None # type: user_agents.parsers.UserAgent
  357. user_language = '' # e.g.: zh-CN
  358. server_host = '' # e.g.: localhost:8080
  359. origin = '' # e.g.: http://localhost:8080
  360. user_ip = ''
  361. backend = '' # one of ['tornado', 'flask', 'django', 'aiohttp']
  362. protocol = '' # one of ['websocket', 'http']
  363. request = None
  364. def get_info():
  365. """Get information about the current session
  366. .. deprecated:: 1.2
  367. Use `info <pywebio.session.info>` instead.
  368. """
  369. global info
  370. import warnings
  371. warnings.warn("`pywebio.session.get_info()` is deprecated since v1.2 and will remove in the future version, "
  372. "please use `pywebio.session.info` instead", DeprecationWarning, stacklevel=2)
  373. return info