__init__.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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:: data
  58. .. autofunction:: set_env
  59. .. autofunction:: go_app
  60. .. data:: info
  61. The session information data object, whose attributes are:
  62. * ``user_agent`` : The Object of the user browser information, whose attributes are
  63. * ``is_mobile`` (bool): whether user agent is identified as a mobile phone (iPhone, Android phones, Blackberry, Windows Phone devices etc)
  64. * ``is_tablet`` (bool): whether user agent is identified as a tablet device (iPad, Kindle Fire, Nexus 7 etc)
  65. * ``is_pc`` (bool): whether user agent is identified to be running a traditional "desktop" OS (Windows, OS X, Linux)
  66. * ``is_touch_capable`` (bool): whether user agent has touch capabilities
  67. * ``browser.family`` (str): Browser family. such as 'Mobile Safari'
  68. * ``browser.version`` (tuple): Browser version. such as (5, 1)
  69. * ``browser.version_string`` (str): Browser version string. such as '5.1'
  70. * ``os.family`` (str): User OS family. such as 'iOS'
  71. * ``os.version`` (tuple): User OS version. such as (5, 1)
  72. * ``os.version_string`` (str): User OS version string. such as '5.1'
  73. * ``device.family`` (str): User agent's device family. such as 'iPhone'
  74. * ``device.brand`` (str): Device brand. such as 'Apple'
  75. * ``device.model`` (str): Device model. such as 'iPhone'
  76. * ``user_language`` (str): Language used by the user's operating system. (e.g., ``'zh-CN'``)
  77. * ``server_host`` (str): PyWebIO server host, including domain and port, the port can be omitted when 80.
  78. * ``origin`` (str): Indicate where the user from. Including protocol, host, and port parts. Such as ``'http://localhost:8080'`` .
  79. 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``).
  80. * ``user_ip`` (str): User's ip address.
  81. * ``backend`` (str): The current PyWebIO backend server implementation. The possible values are ``'tornado'``, ``'flask'``, ``'django'`` , ``'aiohttp'``.
  82. * ``protocol`` (str): The communication protocol between PyWebIO server and browser. The possible values are ``'websocket'``, ``'http'``
  83. * ``request`` (object): The request object when creating the current session. Depending on the backend server, the type of ``request`` can be:
  84. * When using Tornado, ``request`` is instance of
  85. `tornado.httputil.HTTPServerRequest <https://www.tornadoweb.org/en/stable/httputil.html#tornado.httputil.HTTPServerRequest>`_
  86. * When using Flask, ``request`` is instance of `flask.Request <https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data>`_
  87. * When using Django, ``request`` is instance of `django.http.HttpRequest <https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.HttpRequest>`_
  88. * When using aiohttp, ``request`` is instance of `aiohttp.web.BaseRequest <https://docs.aiohttp.org/en/stable/web_reference.html#aiohttp.web.BaseRequest>`_
  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', 'request']
  102. }, indent=4), 'json')
  103. .. autofunction:: get_info
  104. .. autoclass:: pywebio.session.coroutinebased.TaskHandler
  105. :members:
  106. """
  107. import threading
  108. from base64 import b64encode
  109. from functools import wraps
  110. import user_agents
  111. from .base import Session
  112. from .coroutinebased import CoroutineBasedSession
  113. from .threadbased import ThreadBasedSession, ScriptModeSession
  114. from ..exceptions import SessionNotFoundException, SessionException
  115. from ..utils import iscoroutinefunction, isgeneratorfunction, run_as_function, to_coroutine, ObjectDictProxy, \
  116. ReadOnlyObjectDict
  117. # 当前进程中正在使用的会话实现的列表
  118. # List of session implementations currently in use
  119. _active_session_cls = []
  120. __all__ = ['run_async', 'run_asyncio_coroutine', 'register_thread', 'hold', 'defer_call', 'data', 'get_info',
  121. 'run_js', 'eval_js', 'download', 'set_env', 'go_app', 'local', 'info']
  122. def register_session_implement_for_target(target_func):
  123. """根据target_func函数类型注册会话实现,并返回会话实现
  124. Register the session implementation according to the target_func function type, and return the session implementation"""
  125. if iscoroutinefunction(target_func) or isgeneratorfunction(target_func):
  126. cls = CoroutineBasedSession
  127. else:
  128. cls = ThreadBasedSession
  129. if ScriptModeSession in _active_session_cls:
  130. raise RuntimeError("Already in script mode, can't start server")
  131. if cls not in _active_session_cls:
  132. _active_session_cls.append(cls)
  133. return cls
  134. def get_session_implement():
  135. """获取当前会话实现。仅供内部实现使用。应在会话上下文中调用
  136. Get the current session implementation. For internal implementation use only. Should be called in session context"""
  137. if not _active_session_cls:
  138. _active_session_cls.append(ScriptModeSession)
  139. _start_script_mode_server()
  140. # 当前正在使用的会话实现只有一个
  141. # There is only one session implementation currently in use
  142. if len(_active_session_cls) == 1:
  143. return _active_session_cls[0]
  144. # 当前有多个正在使用的会话实现
  145. # There are currently multiple session implementations in use
  146. for cls in _active_session_cls:
  147. try:
  148. cls.get_current_session()
  149. return cls
  150. except SessionNotFoundException:
  151. pass
  152. raise SessionNotFoundException
  153. def _start_script_mode_server():
  154. from ..platform.tornado import start_server_in_current_thread_session
  155. start_server_in_current_thread_session()
  156. def get_current_session() -> "Session":
  157. return get_session_implement().get_current_session()
  158. def get_current_task_id():
  159. return get_session_implement().get_current_task_id()
  160. def check_session_impl(session_type):
  161. def decorator(func):
  162. """装饰器:在函数调用前检查当前会话实现是否满足要求
  163. Decorator: Check whether the current session implementation meets the requirements before the function call"""
  164. @wraps(func)
  165. def inner(*args, **kwargs):
  166. curr_impl = get_session_implement()
  167. # Check if 'now_impl' is a derived from session_type or is the same class
  168. if not issubclass(curr_impl, session_type):
  169. func_name = getattr(func, '__name__', str(func))
  170. require = getattr(session_type, '__name__', str(session_type))
  171. curr = getattr(curr_impl, '__name__', str(curr_impl))
  172. raise RuntimeError("Only can invoke `{func_name:s}` in {require:s} context."
  173. " You are now in {curr:s} context".format(func_name=func_name, require=require,
  174. curr=curr))
  175. return func(*args, **kwargs)
  176. return inner
  177. return decorator
  178. def chose_impl(gen_func):
  179. """
  180. 装饰器,使用chose_impl对gen_func进行装饰后,gen_func() 调用将根据当前会话实现来确定是 返回协程对象 还是 直接运行函数体
  181. 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
  182. """
  183. @wraps(gen_func)
  184. def inner(*args, **kwargs):
  185. gen = gen_func(*args, **kwargs)
  186. if get_session_implement() == CoroutineBasedSession:
  187. return to_coroutine(gen)
  188. else:
  189. return run_as_function(gen)
  190. return inner
  191. @chose_impl
  192. def next_client_event():
  193. res = yield get_current_session().next_client_event()
  194. return res
  195. @chose_impl
  196. def hold():
  197. """Keep the session alive until the browser page is closed by user.
  198. .. note::
  199. 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.
  200. Note: When using :ref:`coroutine-based session <coroutine_based_session>`, you need to use the ``await hold()`` syntax to call the function.
  201. """
  202. while True:
  203. try:
  204. yield next_client_event()
  205. except SessionException:
  206. return
  207. def download(name, content):
  208. """Send file to user, and the user browser will download the file to the local
  209. :param str name: File name when downloading
  210. :param content: File content. It is a bytes-like object
  211. Example:
  212. .. exportable-codeblock::
  213. :name: download
  214. :summary: `download()` usage
  215. put_buttons(['Click to download'], [lambda: download('hello-world.txt', b'hello world!')])
  216. """
  217. from ..io_ctrl import send_msg
  218. content = b64encode(content).decode('ascii')
  219. send_msg('download', spec=dict(name=name, content=content))
  220. def run_js(code_, **args):
  221. """Execute JavaScript code in user browser.
  222. The code is run in the browser's JS global scope.
  223. :param str code_: JavaScript code
  224. :param args: Local variables passed to js code. Variables need to be JSON-serializable.
  225. Example::
  226. run_js('console.log(a + b)', a=1, b=2)
  227. """
  228. from ..io_ctrl import send_msg
  229. send_msg('run_script', spec=dict(code=code_, args=args))
  230. @chose_impl
  231. def eval_js(expression_, **args):
  232. """Execute JavaScript expression in the user's browser and get the value of the expression
  233. :param str expression_: JavaScript expression. The value of the expression need to be JSON-serializable.
  234. :param args: Local variables passed to js code. Variables need to be JSON-serializable.
  235. :return: The value of the expression.
  236. Note: When using :ref:`coroutine-based session <coroutine_based_session>`, you need to use the ``await eval_js(expression)`` syntax to call the function.
  237. Example:
  238. .. exportable-codeblock::
  239. :name: eval_js
  240. :summary: `eval_js()` usage
  241. current_url = eval_js("window.location.href")
  242. put_text(current_url) # ..demo-only
  243. ## ----
  244. function_res = eval_js('''(function(){
  245. var a = 1;
  246. a += b;
  247. return a;
  248. })()''', b=100)
  249. put_text(function_res) # ..demo-only
  250. """
  251. script = r"""
  252. (function(WebIO){
  253. let ____result____ = null; // to avoid naming conflict
  254. try{
  255. ____result____ = eval(%r);
  256. }catch{};
  257. WebIO.sendMessage({
  258. event: "js_yield",
  259. task_id: WebIOCurrentTaskID, // local var in run_script command
  260. data: ____result____ || null
  261. });
  262. })(WebIO);""" % expression_
  263. run_js(script, **args)
  264. res = yield next_client_event()
  265. assert res['event'] == 'js_yield', "Internal Error, please report this bug on " \
  266. "https://github.com/wang0618/PyWebIO/issues"
  267. return res['data']
  268. @check_session_impl(CoroutineBasedSession)
  269. def run_async(coro_obj):
  270. """Run the coroutine object asynchronously. PyWebIO interactive functions are also available in the coroutine.
  271. ``run_async()`` can only be used in :ref:`coroutine-based session <coroutine_based_session>`.
  272. :param coro_obj: Coroutine object
  273. :return: `TaskHandle <pywebio.session.coroutinebased.TaskHandle>` instance, which can be used to query the running status of the coroutine or close the coroutine.
  274. See also: :ref:`Concurrency in coroutine-based sessions <coroutine_based_concurrency>`
  275. """
  276. return get_current_session().run_async(coro_obj)
  277. @check_session_impl(CoroutineBasedSession)
  278. async def run_asyncio_coroutine(coro_obj):
  279. """
  280. 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.
  281. Can only be used in :ref:`coroutine-based session <coroutine_based_session>`.
  282. :param coro_obj: Coroutine object in `asyncio`
  283. Example::
  284. async def app():
  285. put_text('hello')
  286. await run_asyncio_coroutine(asyncio.sleep(1))
  287. put_text('world')
  288. pywebio.platform.flask.start_server(app)
  289. """
  290. return await get_current_session().run_asyncio_coroutine(coro_obj)
  291. @check_session_impl(ThreadBasedSession)
  292. def register_thread(thread: threading.Thread):
  293. """Register the thread so that PyWebIO interactive functions are available in the thread.
  294. Can only be used in the thread-based session.
  295. See :ref:`Concurrent in Server mode <thread_in_server_mode>`
  296. :param threading.Thread thread: Thread object
  297. """
  298. return get_current_session().register_thread(thread)
  299. def defer_call(func):
  300. """Set the function to be called when the session closes.
  301. 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.
  302. You can call ``defer_call(func)`` multiple times in the session, and the set functions will be executed sequentially after the session closes.
  303. ``defer_call()`` can also be used as decorator::
  304. @defer_call
  305. def cleanup():
  306. pass
  307. .. attention:: PyWebIO interactive functions cannot be called inside the function ``func``.
  308. """
  309. get_current_session().defer_call(func)
  310. return func
  311. # session-local data object
  312. local = ObjectDictProxy(lambda: get_current_session().save)
  313. def data():
  314. """Get the session-local object of current session.
  315. .. deprecated:: 1.1
  316. Use `local <pywebio.session.local>` instead.
  317. """
  318. global local
  319. import warnings
  320. warnings.warn("`pywebio.session.data()` is deprecated in v1.1 and will remove in the future version, "
  321. "use `pywebio.session.local` instead", DeprecationWarning, stacklevel=2)
  322. return local
  323. def set_env(**env_info):
  324. """Config the environment of current session.
  325. Available configuration are:
  326. * ``title`` (str): Title of current page.
  327. * ``output_animation`` (bool): Whether to enable output animation, enabled by default
  328. * ``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.
  329. * ``http_pull_interval`` (int): The period of HTTP polling messages (in milliseconds, default 1000ms), only available in sessions based on HTTP connection.
  330. Example::
  331. set_env(title='Awesome PyWebIO!!', output_animation=False)
  332. """
  333. from ..io_ctrl import send_msg
  334. assert all(k in ('title', 'output_animation', 'auto_scroll_bottom', 'http_pull_interval')
  335. for k in env_info.keys())
  336. send_msg('set_env', spec=env_info)
  337. def go_app(name, new_window=True):
  338. """Jump to another task of a same PyWebIO application. Only available in PyWebIO Server mode
  339. :param str name: Target PyWebIO task name.
  340. :param bool new_window: Whether to open in a new window, the default is `True`
  341. See also: :ref:`Server mode <server_and_script_mode>`
  342. """
  343. run_js('javascript:WebIO.openApp(app, new_window)', app=name, new_window=new_window)
  344. # session info data object
  345. info = ReadOnlyObjectDict(lambda: get_current_session().info) # type: _SessionInfoType
  346. class _SessionInfoType:
  347. user_agent = None # type: user_agents.parsers.UserAgent
  348. user_language = '' # e.g.: zh-CN
  349. server_host = '' # e.g.: localhost:8080
  350. origin = '' # e.g.: http://localhost:8080
  351. user_ip = ''
  352. backend = '' # one of ['tornado', 'flask', 'django', 'aiohttp']
  353. protocol = '' # one of ['websocket', 'http']
  354. request = None
  355. def get_info():
  356. """Get information about the current session
  357. .. deprecated:: 1.2
  358. Use `info <pywebio.session.info>` instead.
  359. """
  360. global info
  361. import warnings
  362. warnings.warn("`pywebio.session.get_info()` is deprecated in v1.2 and will remove in the future version, "
  363. "please use `pywebio.session.info` instead", DeprecationWarning, stacklevel=2)
  364. return info