gui.py 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  1. # Copyright 2023 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. from __future__ import annotations
  12. import contextlib
  13. import importlib
  14. import inspect
  15. import json
  16. import os
  17. import pathlib
  18. import re
  19. import sys
  20. import tempfile
  21. import time
  22. import typing as t
  23. import warnings
  24. from importlib import metadata, util
  25. from importlib.util import find_spec
  26. from types import FrameType, SimpleNamespace
  27. from urllib.parse import unquote, urlencode, urlparse
  28. import __main__
  29. import markdown as md_lib
  30. import tzlocal
  31. from flask import Blueprint, Flask, g, jsonify, request, send_file, send_from_directory
  32. from taipy.logger._taipy_logger import _TaipyLogger
  33. from werkzeug.utils import secure_filename
  34. if util.find_spec("pyngrok"):
  35. from pyngrok import ngrok
  36. from ._default_config import _default_stylekit, default_config
  37. from ._page import _Page
  38. from ._renderers import _EmptyPage
  39. from ._renderers._markdown import _TaipyMarkdownExtension
  40. from ._renderers.factory import _Factory
  41. from ._renderers.json import _TaipyJsonEncoder
  42. from ._renderers.utils import _get_columns_dict
  43. from ._warnings import TaipyGuiWarning, _warn
  44. from .builder import _ElementApiGenerator
  45. from .config import Config, ConfigParameter, _Config
  46. from .data.content_accessor import _ContentAccessor
  47. from .data.data_accessor import _DataAccessor, _DataAccessors
  48. from .data.data_format import _DataFormat
  49. from .data.data_scope import _DataScopes
  50. from .extension.library import Element, ElementLibrary
  51. from .gui_types import _WsType
  52. from .page import Page
  53. from .partial import Partial
  54. from .server import _Server
  55. from .state import State
  56. from .utils import (
  57. _delscopeattr,
  58. _filter_locals,
  59. _get_broadcast_var_name,
  60. _get_client_var_name,
  61. _get_css_var_value,
  62. _get_expr_var_name,
  63. _get_module_name_from_frame,
  64. _get_non_existent_file_path,
  65. _get_page_from_module,
  66. _getscopeattr,
  67. _getscopeattr_drill,
  68. _hasscopeattr,
  69. _is_in_notebook,
  70. _LocalsContext,
  71. _MapDict,
  72. _setscopeattr,
  73. _setscopeattr_drill,
  74. _TaipyBase,
  75. _TaipyContent,
  76. _TaipyContentHtml,
  77. _TaipyContentImage,
  78. _TaipyData,
  79. _TaipyLov,
  80. _TaipyLovValue,
  81. _to_camel_case,
  82. _variable_decode,
  83. is_debugging,
  84. )
  85. from .utils._adapter import _Adapter
  86. from .utils._bindings import _Bindings
  87. from .utils._evaluator import _Evaluator
  88. from .utils._variable_directory import _MODULE_ID, _VariableDirectory
  89. from .utils.chart_config_builder import _build_chart_config
  90. from .utils.table_col_builder import _enhance_columns
  91. class _DoNotUpdate:
  92. def __repr__(self):
  93. return "Taipy: Do not update"
  94. class Gui:
  95. """Entry point for the Graphical User Interface generation.
  96. Attributes:
  97. on_action (Callable): The function that is called when a control
  98. triggers an action, as the result of an interaction with the end-user.<br/>
  99. It defaults to the `on_action()` global function defined in the Python
  100. application. If there is no such function, actions will not trigger anything.<br/>
  101. The signature of the *on_action* callback function must be:
  102. - *state*: the `State^` instance of the caller.
  103. - *id* (optional): a string representing the identifier of the caller.
  104. - *payload* (optional): an optional payload from the caller.
  105. on_change (Callable): The function that is called when a control
  106. modifies variables it is bound to, as the result of an interaction with the
  107. end-user.<br/>
  108. It defaults to the `on_change()` global function defined in the Python
  109. application. If there is no such function, user interactions will not trigger
  110. anything.<br/>
  111. The signature of the *on_change* callback function must be:
  112. - *state*: the `State^` instance of the caller.
  113. - *var_name* (str): The name of the variable that triggered this callback.
  114. - *var_value* (any): The new value for this variable.
  115. on_init (Callable): The function that is called on the first connection of a new client.<br/>
  116. It defaults to the `on_init()` global function defined in the Python
  117. application. If there is no such function, the first connection will not trigger
  118. anything.<br/>
  119. The signature of the *on_init* callback function must be:
  120. - *state*: the `State^` instance of the caller.
  121. on_navigate (Callable): The function that is called when a page is requested.<br/>
  122. It defaults to the `on_navigate()` global function defined in the Python
  123. application. If there is no such function, page requests will not trigger
  124. anything.<br/>
  125. The signature of the *on_navigate* callback function must be:
  126. - *state*: the `State^` instance of the caller.
  127. - *page_name*: the name of the page the user is navigating to.
  128. - *params* (Optional): the query parameters provided in the URL.
  129. The *on_navigate* callback function must return the name of the page the user should be
  130. directed to.
  131. on_exception (Callable): The function that is called an exception occurs on user code.<br/>
  132. It defaults to the `on_exception()` global function defined in the Python
  133. application. If there is no such function, exceptions will not trigger
  134. anything.<br/>
  135. The signature of the *on_exception* callback function must be:
  136. - *state*: the `State^` instance of the caller.
  137. - *function_name*: the name of the function that raised the exception.
  138. - *exception*: the exception object that was raised.
  139. on_status (Callable): The function that is called when the status page is shown.<br/>
  140. It defaults to the `on_status()` global function defined in the Python
  141. application. If there is no such function, status page content shows only the status of the
  142. server.<br/>
  143. The signature of the *on_status* callback function must be:
  144. - *state*: the `State^` instance of the caller.
  145. It must return raw and valid HTML content as a string.
  146. on_user_content (Callable): The function that is called when a specific URL (generated by
  147. `get_user_content_url()^`) is requested.<br/>
  148. This callback function must return the raw HTML content of the page to be displayed on
  149. the browser.
  150. This attribute defaults to the `on_user_content()` global function defined in the Python
  151. application. If there is no such function, those specific URLs will not trigger
  152. anything.<br/>
  153. The signature of the *on_user_content* callback function must be:
  154. - *state*: the `State^` instance of the caller.
  155. - *path*: the path provided to the `get_user_content_url()^` to build the URL.
  156. - *parameters*: An optional dictionary as defined in the `get_user_content_url()^` call.
  157. The returned HTML content can therefore use both the variables stored in the *state*
  158. and the parameters provided in the call to `get_user_content_url()^`.
  159. state (State^): **Only defined when running in an IPython notebook context.**<br/>
  160. The unique instance of `State^` that you can use to change bound variables
  161. directly, potentially impacting the user interface in real-time.
  162. !!! note
  163. This class belongs to and is documented in the `taipy.gui` package but it is
  164. accessible from the top `taipy` package to simplify its access, allowing to
  165. use:
  166. ```py
  167. from taipy import Gui
  168. ```
  169. """
  170. __root_page_name = "TaiPy_root_page"
  171. __env_filename = "taipy.gui.env"
  172. __UI_BLOCK_NAME = "TaipyUiBlockVar"
  173. __MESSAGE_GROUPING_NAME = "TaipyMessageGrouping"
  174. __ON_INIT_NAME = "TaipyOnInit"
  175. __ARG_CLIENT_ID = "client_id"
  176. __INIT_URL = "taipy-init"
  177. __JSX_URL = "taipy-jsx"
  178. __CONTENT_ROOT = "taipy-content"
  179. __UPLOAD_URL = "taipy-uploads"
  180. _EXTENSION_ROOT = "taipy-extension"
  181. __USER_CONTENT_URL = "taipy-user-content"
  182. __BROADCAST_G_ID = "taipy_broadcasting"
  183. __BRDCST_CALLBACK_G_ID = "taipy_brdcst_callback"
  184. __SELF_VAR = "__gui"
  185. __DO_NOT_UPDATE_VALUE = _DoNotUpdate()
  186. _HTML_CONTENT_KEY = "__taipy_html_content"
  187. __USER_CONTENT_CB = "custom_user_content_cb"
  188. __RE_HTML = re.compile(r"(.*?)\.html$")
  189. __RE_MD = re.compile(r"(.*?)\.md$")
  190. __RE_PY = re.compile(r"(.*?)\.py$")
  191. __RE_PAGE_NAME = re.compile(r"^[\w\-\/]+$")
  192. __reserved_routes: t.List[str] = [
  193. __INIT_URL,
  194. __JSX_URL,
  195. __CONTENT_ROOT,
  196. __UPLOAD_URL,
  197. _EXTENSION_ROOT,
  198. __USER_CONTENT_URL,
  199. ]
  200. __LOCAL_TZ = str(tzlocal.get_localzone())
  201. __extensions: t.Dict[str, t.List[ElementLibrary]] = {}
  202. __shared_variables: t.List[str] = []
  203. __content_providers: t.Dict[type, t.Callable[..., str]] = {}
  204. def __init__(
  205. self,
  206. page: t.Optional[t.Union[str, Page]] = None,
  207. pages: t.Optional[dict] = None,
  208. css_file: t.Optional[str] = None,
  209. path_mapping: t.Optional[dict] = {},
  210. env_filename: t.Optional[str] = None,
  211. libraries: t.Optional[t.List[ElementLibrary]] = None,
  212. flask: t.Optional[Flask] = None,
  213. ):
  214. """Initialize a new Gui instance.
  215. Arguments:
  216. page (Optional[Union[str, Page^]]): An optional `Page^` instance that is used
  217. when there is a single page in this interface, referenced as the *root*
  218. page (located at `/`).<br/>
  219. If *page* is a raw string and if it holds a path to a readable file then
  220. a `Markdown^` page is built from the content of that file.<br/>
  221. If *page* is a string that does not indicate a path to readable file then
  222. a `Markdown^` page is built from that string.<br/>
  223. Note that if *pages* is provided, those pages are added as well.
  224. pages (Optional[dict]): Used if you want to initialize this instance with a set
  225. of pages.<br/>
  226. The method `(Gui.)add_pages(pages)^` is called if *pages* is not None.
  227. You can find details on the possible values of this argument in the
  228. documentation for this method.
  229. css_file (Optional[str]): A pathname to a CSS file that gets used as a style sheet in
  230. all the pages.<br/>
  231. The default value is a file that has the same base name as the Python
  232. file defining the `main` function, sitting next to this Python file,
  233. with the `.css` extension.
  234. path_mapping (Optional[dict]): A dictionary that associates a URL prefix to
  235. a path in the server file system.<br/>
  236. If the assets of your application are located in */home/me/app_assets* and
  237. you want to access them using only '*assets*' in your application, you can
  238. set *path_mapping={"assets": "/home/me/app_assets"}*. If your application
  239. then requests the file *"/assets/images/logo.png"*, the server searches
  240. for the file *"/home/me/app_assets/images/logo.png"*.<br/>
  241. If empty or not defined, access through the browser to all resources under the directory
  242. of the main Python file is allowed.
  243. env_filename (Optional[str]): An optional file from which to load application
  244. configuration variables (see the
  245. [Configuration](../gui/configuration.md#configuring-the-gui-instance) section
  246. of the User Manual for details.)<br/>
  247. The default value is "taipy.gui.env"
  248. libraries (Optional[List[ElementLibrary]]): An optional list of extension library
  249. instances that pages can reference.<br/>
  250. Using this argument is equivalent to calling `(Gui.)add_library()^` for each
  251. list's elements.
  252. flask (Optional[Flask]): An optional instance of a Flask application object.<br/>
  253. If this argument is set, this `Gui` instance will use the value of this argument
  254. as the underlying server. If omitted or set to None, this `Gui` will create its
  255. own Flask application instance and use it to serve the pages.
  256. """
  257. # store suspected local containing frame
  258. self.__frame = t.cast(FrameType, t.cast(FrameType, inspect.currentframe()).f_back)
  259. self.__default_module_name = _get_module_name_from_frame(self.__frame)
  260. self._set_css_file(css_file)
  261. # Preserve server config for server initialization
  262. self._path_mapping = path_mapping
  263. self._flask = flask
  264. self._config = _Config()
  265. self.__content_accessor = None
  266. self._accessors = _DataAccessors()
  267. self.__state: t.Optional[State] = None
  268. self.__bindings = _Bindings(self)
  269. self.__locals_context = _LocalsContext()
  270. self.__var_dir = _VariableDirectory(self.__locals_context)
  271. self.__evaluator: _Evaluator = None # type: ignore
  272. self.__adapter = _Adapter()
  273. self.__directory_name_of_pages: t.List[str] = []
  274. # default actions
  275. self.on_action: t.Optional[t.Callable] = None
  276. self.on_change: t.Optional[t.Callable] = None
  277. self.on_init: t.Optional[t.Callable] = None
  278. self.on_navigate: t.Optional[t.Callable] = None
  279. self.on_exception: t.Optional[t.Callable] = None
  280. self.on_status: t.Optional[t.Callable] = None
  281. self.on_user_content: t.Optional[t.Callable] = None
  282. # sid from client_id
  283. self.__client_id_2_sid: t.Dict[str, t.Set[str]] = {}
  284. # Load default config
  285. self._flask_blueprint: t.List[Blueprint] = []
  286. self._config._load(default_config)
  287. # get taipy version
  288. try:
  289. gui_file = pathlib.Path(__file__ or ".").resolve()
  290. with open(gui_file.parent / "version.json") as version_file:
  291. self.__version = json.load(version_file)
  292. except Exception as e: # pragma: no cover
  293. _warn("Cannot retrieve version.json file", e)
  294. self.__version = {}
  295. # Load Markdown extension
  296. # NOTE: Make sure, if you change this extension list, that the User Manual gets updated.
  297. # There's a section that explicitly lists these extensions in
  298. # docs/gui/pages.md#markdown-specifics
  299. self._markdown = md_lib.Markdown(
  300. extensions=[
  301. "fenced_code",
  302. "meta",
  303. "admonition",
  304. "sane_lists",
  305. "tables",
  306. "attr_list",
  307. "md_in_html",
  308. _TaipyMarkdownExtension(gui=self),
  309. ]
  310. )
  311. if page:
  312. self.add_page(name=Gui.__root_page_name, page=page)
  313. if pages is not None:
  314. self.add_pages(pages)
  315. if env_filename is not None:
  316. self.__env_filename = env_filename
  317. if libraries is not None:
  318. for library in libraries:
  319. Gui.add_library(library)
  320. @staticmethod
  321. def add_library(library: ElementLibrary) -> None:
  322. """Add a custom visual element library.
  323. This application will be able to use custom visual elements defined in this library.
  324. Arguments:
  325. library: The custom visual element library to add to this application.
  326. Multiple libraries with the same name can be added. This allows to split multiple custom visual
  327. elements in several `ElementLibrary^` instances, but still refer to these elements with the same
  328. prefix in the page definitions.
  329. """
  330. if isinstance(library, ElementLibrary):
  331. _Factory.set_library(library)
  332. library_name = library.get_name()
  333. if library_name.isidentifier():
  334. libs = Gui.__extensions.get(library_name)
  335. if libs is None:
  336. Gui.__extensions[library_name] = [library]
  337. else:
  338. libs.append(library)
  339. _ElementApiGenerator().add_library(library)
  340. else:
  341. raise NameError(f"ElementLibrary passed to add_library() has an invalid name: '{library_name}'")
  342. else: # pragma: no cover
  343. raise RuntimeError(
  344. f"add_library() argument should be a subclass of ElementLibrary instead of '{type(library)}'"
  345. )
  346. @staticmethod
  347. def register_content_provider(content_type: type, content_provider: t.Callable[..., str]) -> None:
  348. """Add a custom content provider.
  349. The application can use custom content for the `part` block when its *content* property is set to an object with type *type*.
  350. Arguments:
  351. content_type: The type of the content that triggers the content provider.
  352. content_provider: The function that converts content of type *type* into an HTML string.
  353. """ # noqa: E501
  354. if Gui.__content_providers.get(content_type):
  355. _warn(f"The type {content_type} is already associated with a provider.")
  356. return
  357. if not callable(content_provider):
  358. _warn(f"The provider for {content_type} must be a function.")
  359. return
  360. Gui.__content_providers[content_type] = content_provider
  361. def __process_content_provider(self, state: State, path: str, query: t.Dict[str, str]):
  362. variable_name = query.get("variable_name")
  363. content = None
  364. if variable_name:
  365. content = _getscopeattr(self, variable_name)
  366. if isinstance(content, _TaipyContentHtml):
  367. content = content.get()
  368. provider_fn = Gui.__content_providers.get(type(content))
  369. if provider_fn is None:
  370. # try plotly
  371. if find_spec("plotly") and find_spec("plotly.graph_objs"):
  372. from plotly.graph_objs import Figure as PlotlyFigure
  373. if isinstance(content, PlotlyFigure):
  374. def get_plotly_content(figure: PlotlyFigure):
  375. return figure.to_html()
  376. Gui.register_content_provider(PlotlyFigure, get_plotly_content)
  377. provider_fn = get_plotly_content
  378. if provider_fn is None:
  379. # try matplotlib
  380. if find_spec("matplotlib") and find_spec("matplotlib.figure"):
  381. from matplotlib.figure import Figure as MatplotlibFigure
  382. if isinstance(content, MatplotlibFigure):
  383. def get_matplotlib_content(figure: MatplotlibFigure):
  384. import base64
  385. from io import BytesIO
  386. buf = BytesIO()
  387. figure.savefig(buf, format="png")
  388. data = base64.b64encode(buf.getbuffer()).decode("ascii")
  389. return f'<img src="data:image/png;base64,{data}"/>'
  390. Gui.register_content_provider(MatplotlibFigure, get_matplotlib_content)
  391. provider_fn = get_matplotlib_content
  392. if callable(provider_fn):
  393. try:
  394. return provider_fn(content)
  395. except Exception as e:
  396. _warn(f"Error in content provider for type {str(type(content))}", e)
  397. return (
  398. '<div style="background:white;color:red;">'
  399. + (f"No valid provider for type {type(content).__name__}" if content else "Wrong context.")
  400. + "</div>"
  401. )
  402. @staticmethod
  403. def add_shared_variable(*names: str) -> None:
  404. """Add shared variables.
  405. The variables will be synchronized between all clients when updated.
  406. Note that only variables from the main module will be registered.
  407. This is a synonym for `(Gui.)add_shared_variables()^`.
  408. Arguments:
  409. names: The names of the variables that become shared, as a list argument.
  410. """
  411. for name in names:
  412. if name not in Gui.__shared_variables:
  413. Gui.__shared_variables.append(name)
  414. @staticmethod
  415. def add_shared_variables(*names: str) -> None:
  416. """Add shared variables.
  417. The variables will be synchronized between all clients when updated.
  418. Note that only variables from the main module will be registered.
  419. This is a synonym for `(Gui.)add_shared_variable()^`.
  420. Arguments:
  421. names: The names of the variables that become shared, as a list argument.
  422. """
  423. Gui.add_shared_variable(*names)
  424. def _get_shared_variables(self) -> t.List[str]:
  425. return self.__evaluator.get_shared_variables()
  426. def __get_content_accessor(self):
  427. if self.__content_accessor is None:
  428. self.__content_accessor = _ContentAccessor(self._get_config("data_url_max_size", 50 * 1024))
  429. return self.__content_accessor
  430. def _bindings(self):
  431. return self.__bindings
  432. def _get_data_scope(self) -> SimpleNamespace:
  433. return self.__bindings._get_data_scope()
  434. def _get_all_data_scopes(self) -> t.Dict[str, SimpleNamespace]:
  435. return self.__bindings._get_all_scopes()
  436. def _get_config(self, name: ConfigParameter, default_value: t.Any) -> t.Any:
  437. return self._config._get_config(name, default_value)
  438. def _get_themes(self) -> t.Optional[t.Dict[str, t.Any]]:
  439. theme = self._get_config("theme", None)
  440. dark_theme = self._get_config("dark_theme", None)
  441. light_theme = self._get_config("light_theme", None)
  442. res = {}
  443. if theme:
  444. res["base"] = theme
  445. if dark_theme:
  446. res["dark"] = dark_theme
  447. if light_theme:
  448. res["light"] = light_theme
  449. return res if theme or dark_theme or light_theme else None
  450. def _bind(self, name: str, value: t.Any) -> None:
  451. self._bindings()._bind(name, value)
  452. def __get_state(self):
  453. return self.__state
  454. def _get_client_id(self) -> str:
  455. return (
  456. _DataScopes._GLOBAL_ID
  457. if self._bindings()._is_single_client()
  458. else getattr(g, Gui.__ARG_CLIENT_ID, "unknown id")
  459. )
  460. def __set_client_id_in_context(self, client_id: t.Optional[str] = None, force=False):
  461. if not client_id and request:
  462. client_id = request.args.get(Gui.__ARG_CLIENT_ID, "")
  463. if not client_id and force:
  464. res = self._bindings()._get_or_create_scope("")
  465. client_id = res[0] if res[1] else None
  466. if client_id and request:
  467. if sid := getattr(request, "sid", None):
  468. sids = self.__client_id_2_sid.get(client_id, None)
  469. if sids is None:
  470. sids = set()
  471. self.__client_id_2_sid[client_id] = sids
  472. sids.add(sid)
  473. g.client_id = client_id
  474. def __is_var_modified_in_context(self, var_name: str, derived_vars: t.Set[str]) -> bool:
  475. modified_vars: t.Optional[t.Set[str]] = getattr(g, "modified_vars", None)
  476. der_vars: t.Optional[t.Set[str]] = getattr(g, "derived_vars", None)
  477. setattr(g, "update_count", getattr(g, "update_count", 0) + 1)
  478. if modified_vars is None:
  479. modified_vars = set()
  480. g.modified_vars = modified_vars
  481. if der_vars is None:
  482. g.derived_vars = derived_vars
  483. else:
  484. der_vars.update(derived_vars)
  485. if var_name in modified_vars:
  486. return True
  487. modified_vars.add(var_name)
  488. return False
  489. def __clean_vars_on_exit(self) -> t.Optional[t.Set[str]]:
  490. update_count = getattr(g, "update_count", 0) - 1
  491. if update_count < 1:
  492. derived_vars: t.Set[str] = getattr(g, "derived_vars", set())
  493. delattr(g, "update_count")
  494. delattr(g, "modified_vars")
  495. delattr(g, "derived_vars")
  496. return derived_vars
  497. else:
  498. setattr(g, "update_count", update_count)
  499. return None
  500. def _manage_message(self, msg_type: _WsType, message: dict) -> None:
  501. try:
  502. client_id = None
  503. if msg_type == _WsType.CLIENT_ID.value:
  504. res = self._bindings()._get_or_create_scope(message.get("payload", ""))
  505. client_id = res[0] if res[1] else None
  506. self.__set_client_id_in_context(client_id or message.get(Gui.__ARG_CLIENT_ID))
  507. with self._set_locals_context(message.get("module_context") or None):
  508. if msg_type == _WsType.UPDATE.value:
  509. payload = message.get("payload", {})
  510. self.__front_end_update(
  511. str(message.get("name")),
  512. payload.get("value"),
  513. message.get("propagate", True),
  514. payload.get("relvar"),
  515. payload.get("on_change"),
  516. )
  517. elif msg_type == _WsType.ACTION.value:
  518. self.__on_action(message.get("name"), message.get("payload"))
  519. elif msg_type == _WsType.DATA_UPDATE.value:
  520. self.__request_data_update(str(message.get("name")), message.get("payload"))
  521. elif msg_type == _WsType.REQUEST_UPDATE.value:
  522. self.__request_var_update(message.get("payload"))
  523. self.__send_ack(message.get("ack_id"))
  524. except Exception as e: # pragma: no cover
  525. _warn(f"Decoding Message has failed: {message}", e)
  526. def __front_end_update(
  527. self,
  528. var_name: str,
  529. value: t.Any,
  530. propagate=True,
  531. rel_var: t.Optional[str] = None,
  532. on_change: t.Optional[str] = None,
  533. ) -> None:
  534. if not var_name:
  535. return
  536. # Check if Variable is a managed type
  537. current_value = _getscopeattr_drill(self, self.__evaluator.get_hash_from_expr(var_name))
  538. if isinstance(current_value, _TaipyData):
  539. return
  540. elif rel_var and isinstance(current_value, _TaipyLovValue): # pragma: no cover
  541. lov_holder = _getscopeattr_drill(self, self.__evaluator.get_hash_from_expr(rel_var))
  542. if isinstance(lov_holder, _TaipyLov):
  543. val = value if isinstance(value, list) else [value]
  544. elt_4_ids = self.__adapter._get_elt_per_ids(lov_holder.get_name(), lov_holder.get())
  545. ret_val = [elt_4_ids.get(x, x) for x in val]
  546. if isinstance(value, list):
  547. value = ret_val
  548. elif ret_val:
  549. value = ret_val[0]
  550. elif isinstance(current_value, _TaipyBase):
  551. value = current_value.cast_value(value)
  552. self._update_var(
  553. var_name, value, propagate, current_value if isinstance(current_value, _TaipyBase) else None, on_change
  554. )
  555. def _update_var(
  556. self,
  557. var_name: str,
  558. value: t.Any,
  559. propagate=True,
  560. holder: t.Optional[_TaipyBase] = None,
  561. on_change: t.Optional[str] = None,
  562. ) -> None:
  563. if holder:
  564. var_name = holder.get_name()
  565. hash_expr = self.__evaluator.get_hash_from_expr(var_name)
  566. derived_vars = {hash_expr}
  567. # set to broadcast mode if hash_expr is in shared_variable
  568. if hash_expr in self._get_shared_variables():
  569. self._set_broadcast()
  570. # Use custom attrsetter function to allow value binding for _MapDict
  571. if propagate:
  572. _setscopeattr_drill(self, hash_expr, value)
  573. # In case expression == hash (which is when there is only a single variable in expression)
  574. if var_name == hash_expr or hash_expr.startswith("tpec_"):
  575. derived_vars.update(self._re_evaluate_expr(var_name))
  576. elif holder:
  577. derived_vars.update(self._evaluate_holders(hash_expr))
  578. # if the variable has been evaluated then skip updating to prevent infinite loop
  579. var_modified = self.__is_var_modified_in_context(hash_expr, derived_vars)
  580. if not var_modified:
  581. self._call_on_change(
  582. var_name,
  583. value.get() if isinstance(value, _TaipyBase) else value._dict if isinstance(value, _MapDict) else value,
  584. on_change,
  585. )
  586. derived_modified = self.__clean_vars_on_exit()
  587. if derived_modified is not None:
  588. self.__send_var_list_update(list(derived_modified), var_name)
  589. def _get_real_var_name(self, var_name: str) -> t.Tuple[str, str]:
  590. if not var_name:
  591. return (var_name, var_name)
  592. # Handle holder prefix if needed
  593. if var_name.startswith(_TaipyBase._HOLDER_PREFIX):
  594. for hp in _TaipyBase._get_holder_prefixes():
  595. if var_name.startswith(hp):
  596. var_name = var_name[len(hp) :]
  597. break
  598. suffix_var_name = ""
  599. if "." in var_name:
  600. first_dot_index = var_name.index(".")
  601. suffix_var_name = var_name[first_dot_index + 1 :]
  602. var_name = var_name[:first_dot_index]
  603. var_name_decode, module_name = _variable_decode(self._get_expr_from_hash(var_name))
  604. current_context = self._get_locals_context()
  605. # #583: allow module resolution for var_name in current_context root_page context
  606. if (
  607. module_name
  608. and self._config.root_page
  609. and self._config.root_page._renderer
  610. and self._config.root_page._renderer._get_module_name() == module_name
  611. ):
  612. return f"{var_name_decode}.{suffix_var_name}" if suffix_var_name else var_name_decode, module_name
  613. if module_name == current_context:
  614. var_name = var_name_decode
  615. else:
  616. if var_name not in self.__var_dir._var_head:
  617. raise NameError(f"Can't find matching variable for {var_name} on context: {current_context}")
  618. _found = False
  619. for k, v in self.__var_dir._var_head[var_name]:
  620. if v == current_context:
  621. var_name = k
  622. _found = True
  623. break
  624. if not _found: # pragma: no cover
  625. raise NameError(f"Can't find matching variable for {var_name} on context: {current_context}")
  626. return f"{var_name}.{suffix_var_name}" if suffix_var_name else var_name, current_context
  627. def _call_on_change(self, var_name: str, value: t.Any, on_change: t.Optional[str] = None):
  628. try:
  629. var_name, current_context = self._get_real_var_name(var_name)
  630. except Exception as e: # pragma: no cover
  631. _warn("", e)
  632. return
  633. on_change_fn = self._get_user_function(on_change) if on_change else None
  634. if not callable(on_change_fn):
  635. on_change_fn = self._get_user_function("on_change")
  636. if callable(on_change_fn):
  637. try:
  638. argcount = on_change_fn.__code__.co_argcount
  639. if argcount > 0 and inspect.ismethod(on_change_fn):
  640. argcount -= 1
  641. args: t.List[t.Any] = [None for _ in range(argcount)]
  642. if argcount > 0:
  643. args[0] = self.__get_state()
  644. if argcount > 1:
  645. args[1] = var_name
  646. if argcount > 2:
  647. args[2] = value
  648. if argcount > 3:
  649. args[3] = current_context
  650. on_change_fn(*args)
  651. except Exception as e: # pragma: no cover
  652. if not self._call_on_exception(on_change or "on_change", e):
  653. _warn(f"{on_change or 'on_change'}(): callback function raised an exception", e)
  654. def _get_content(self, var_name: str, value: t.Any, image: bool) -> t.Any:
  655. ret_value = self.__get_content_accessor().get_info(var_name, value, image)
  656. return f"/{Gui.__CONTENT_ROOT}/{ret_value[0]}" if isinstance(ret_value, tuple) else ret_value
  657. def __serve_content(self, path: str) -> t.Any:
  658. self.__set_client_id_in_context()
  659. parts = path.split("/")
  660. if len(parts) > 1:
  661. file_name = parts[-1]
  662. (dir_path, as_attachment) = self.__get_content_accessor().get_content_path(
  663. path[: -len(file_name) - 1], file_name, request.args.get("bypass")
  664. )
  665. if dir_path:
  666. return send_from_directory(str(dir_path), file_name, as_attachment=as_attachment)
  667. return ("", 404)
  668. def _get_user_content_url(
  669. self, path: t.Optional[str] = None, query_args: t.Optional[t.Dict[str, str]] = None
  670. ) -> t.Optional[str]:
  671. qargs = query_args or {}
  672. qargs.update({Gui.__ARG_CLIENT_ID: self._get_client_id()})
  673. return f"/{Gui.__USER_CONTENT_URL}/{path or 'TaIpY'}?{urlencode(qargs)}"
  674. def __serve_user_content(self, path: str) -> t.Any:
  675. self.__set_client_id_in_context()
  676. qargs: t.Dict[str, str] = {}
  677. qargs.update(request.args)
  678. qargs.pop(Gui.__ARG_CLIENT_ID, None)
  679. cb_function: t.Optional[t.Union[t.Callable, str]] = None
  680. cb_function_name = None
  681. if qargs.get(Gui._HTML_CONTENT_KEY):
  682. cb_function = self.__process_content_provider
  683. cb_function_name = cb_function.__name__
  684. else:
  685. cb_function_name = qargs.get(Gui.__USER_CONTENT_CB)
  686. if cb_function_name:
  687. cb_function = self._get_user_function(cb_function_name)
  688. if not callable(cb_function):
  689. parts = cb_function_name.split(".", 1)
  690. if len(parts) > 1:
  691. base = _getscopeattr(self, parts[0], None)
  692. if base and (meth := getattr(base, parts[1], None)):
  693. cb_function = meth
  694. else:
  695. base = self.__evaluator._get_instance_in_context(parts[0])
  696. if base and (meth := getattr(base, parts[1], None)):
  697. cb_function = meth
  698. if not callable(cb_function):
  699. _warn(f"{cb_function_name}() callback function has not been defined.")
  700. cb_function = None
  701. if cb_function is None:
  702. cb_function_name = "on_user_content"
  703. if hasattr(self, cb_function_name) and callable(self.on_user_content):
  704. cb_function = self.on_user_content
  705. else:
  706. _warn("on_user_content() callback function has not been defined.")
  707. if callable(cb_function):
  708. try:
  709. args: t.List[t.Any] = []
  710. if path:
  711. args.append(path)
  712. if len(qargs):
  713. args.append(qargs)
  714. ret = self._call_function_with_state(cb_function, args)
  715. if ret is None:
  716. _warn(f"{cb_function_name}() callback function must return a value.")
  717. else:
  718. return (ret, 200)
  719. except Exception as e: # pragma: no cover
  720. if not self._call_on_exception(str(cb_function_name), e):
  721. _warn(f"{cb_function_name}() callback function raised an exception", e)
  722. return ("", 404)
  723. def __serve_extension(self, path: str) -> t.Any:
  724. parts = path.split("/")
  725. last_error = ""
  726. resource_name = None
  727. if len(parts) > 1:
  728. libs = Gui.__extensions.get(parts[0], [])
  729. for library in libs:
  730. try:
  731. resource_name = library.get_resource("/".join(parts[1:]))
  732. if resource_name:
  733. return send_file(resource_name)
  734. except Exception as e:
  735. last_error = f"\n{e}" # Check if the resource is served by another library with the same name
  736. _warn(f"Resource '{resource_name or path}' not accessible for library '{parts[0]}'{last_error}")
  737. return ("", 404)
  738. def __get_version(self) -> str:
  739. return f'{self.__version.get("major", 0)}.{self.__version.get("minor", 0)}.{self.__version.get("patch", 0)}'
  740. def __append_libraries_to_status(self, status: t.Dict[str, t.Any]):
  741. libraries: t.Dict[str, t.Any] = {}
  742. for libs_list in self.__extensions.values():
  743. for lib in libs_list:
  744. if not isinstance(lib, ElementLibrary):
  745. continue
  746. libs = libraries.get(lib.get_name())
  747. if libs is None:
  748. libs = []
  749. libraries[lib.get_name()] = libs
  750. elts: t.List[t.Dict[str, str]] = []
  751. libs.append({"js module": lib.get_js_module_name(), "elements": elts})
  752. for element_name, elt in lib.get_elements().items():
  753. if not isinstance(elt, Element):
  754. continue
  755. elt_dict = {"name": element_name}
  756. if hasattr(elt, "_render_xhtml"):
  757. elt_dict["render function"] = elt._render_xhtml.__code__.co_name
  758. else:
  759. elt_dict["react name"] = elt._get_js_name(element_name)
  760. elts.append(elt_dict)
  761. status.update({"libraries": libraries})
  762. def _serve_status(self, template: pathlib.Path) -> t.Dict[str, t.Dict[str, str]]:
  763. base_json: t.Dict[str, t.Any] = {"user_status": str(self.__call_on_status() or "")}
  764. if self._get_config("extended_status", False):
  765. base_json.update(
  766. {
  767. "flask_version": str(metadata.version("flask") or ""),
  768. "backend_version": self.__get_version(),
  769. "host": f'{self._get_config("host", "localhost")}:{self._get_config("port", "default")}',
  770. "python_version": sys.version,
  771. }
  772. )
  773. self.__append_libraries_to_status(base_json)
  774. try:
  775. base_json.update(json.loads(template.read_text()))
  776. except Exception as e: # pragma: no cover
  777. _warn(f"Exception raised reading JSON in '{template}'", e)
  778. return {"gui": base_json}
  779. def __upload_files(self):
  780. self.__set_client_id_in_context()
  781. if "var_name" not in request.form:
  782. _warn("No var name")
  783. return ("No var name", 400)
  784. var_name = request.form["var_name"]
  785. multiple = "multiple" in request.form and request.form["multiple"] == "True"
  786. if "blob" not in request.files:
  787. _warn("No file part")
  788. return ("No file part", 400)
  789. file = request.files["blob"]
  790. # If the user does not select a file, the browser submits an
  791. # empty file without a filename.
  792. if file.filename == "":
  793. _warn("No selected file")
  794. return ("No selected file", 400)
  795. suffix = ""
  796. complete = True
  797. part = 0
  798. if "total" in request.form:
  799. total = int(request.form["total"])
  800. if total > 1 and "part" in request.form:
  801. part = int(request.form["part"])
  802. suffix = f".part.{part}"
  803. complete = part == total - 1
  804. if file: # and allowed_file(file.filename)
  805. upload_path = pathlib.Path(self._get_config("upload_folder", tempfile.gettempdir())).resolve()
  806. file_path = _get_non_existent_file_path(upload_path, secure_filename(file.filename))
  807. file.save(str(upload_path / (file_path.name + suffix)))
  808. if complete:
  809. if part > 0:
  810. try:
  811. with open(file_path, "wb") as grouped_file:
  812. for nb in range(part + 1):
  813. with open(upload_path / f"{file_path.name}.part.{nb}", "rb") as part_file:
  814. grouped_file.write(part_file.read())
  815. except EnvironmentError as ee: # pragma: no cover
  816. _warn("Cannot group file after chunk upload", ee)
  817. return
  818. # notify the file is uploaded
  819. newvalue = str(file_path)
  820. if multiple:
  821. value = _getscopeattr(self, var_name)
  822. if not isinstance(value, t.List):
  823. value = [] if value is None else [value]
  824. value.append(newvalue)
  825. newvalue = value
  826. setattr(self._bindings(), var_name, newvalue)
  827. return ("", 200)
  828. _data_request_counter = 1
  829. def __send_var_list_update( # noqa C901
  830. self,
  831. modified_vars: t.List[str],
  832. front_var: t.Optional[str] = None,
  833. ):
  834. ws_dict = {}
  835. values = {v: _getscopeattr_drill(self, v) for v in modified_vars}
  836. for k, v in values.items():
  837. if isinstance(v, (_TaipyData, _TaipyContentHtml)) and v.get_name() in modified_vars:
  838. modified_vars.remove(v.get_name())
  839. elif isinstance(v, _DoNotUpdate):
  840. modified_vars.remove(k)
  841. for _var in modified_vars:
  842. newvalue = values.get(_var)
  843. if isinstance(newvalue, _TaipyData):
  844. # A changing integer that triggers a data request
  845. newvalue = Gui._data_request_counter
  846. Gui._data_request_counter = (Gui._data_request_counter % 100) + 1
  847. else:
  848. if isinstance(newvalue, (_TaipyContent, _TaipyContentImage)):
  849. ret_value = self.__get_content_accessor().get_info(
  850. front_var, newvalue.get(), isinstance(newvalue, _TaipyContentImage)
  851. )
  852. if isinstance(ret_value, tuple):
  853. newvalue = f"/{Gui.__CONTENT_ROOT}/{ret_value[0]}"
  854. else:
  855. newvalue = ret_value
  856. elif isinstance(newvalue, _TaipyContentHtml):
  857. newvalue = self._get_user_content_url(
  858. None, {"variable_name": str(_var), Gui._HTML_CONTENT_KEY: str(time.time())}
  859. )
  860. elif isinstance(newvalue, _TaipyLov):
  861. newvalue = [self.__adapter._run_for_var(newvalue.get_name(), elt) for elt in newvalue.get()]
  862. elif isinstance(newvalue, _TaipyLovValue):
  863. if isinstance(newvalue.get(), list):
  864. newvalue = [
  865. self.__adapter._run_for_var(newvalue.get_name(), elt, id_only=True)
  866. for elt in newvalue.get()
  867. ]
  868. else:
  869. newvalue = self.__adapter._run_for_var(newvalue.get_name(), newvalue.get(), id_only=True)
  870. if isinstance(newvalue, (dict, _MapDict)):
  871. continue # this var has no transformer
  872. debug_warnings: t.List[warnings.WarningMessage] = []
  873. with warnings.catch_warnings(record=True) as warns:
  874. warnings.resetwarnings()
  875. json.dumps(newvalue, cls=_TaipyJsonEncoder)
  876. if len(warns):
  877. keep_value = True
  878. for w in list(warns):
  879. if is_debugging():
  880. debug_warnings.append(w)
  881. if w.category is not DeprecationWarning and w.category is not PendingDeprecationWarning:
  882. keep_value = False
  883. break
  884. if not keep_value:
  885. # do not send data that is not serializable
  886. continue
  887. for w in debug_warnings:
  888. warnings.warn(w.message, w.category)
  889. ws_dict[_var] = newvalue
  890. # TODO: What if value == newvalue?
  891. self.__send_ws_update_with_dict(ws_dict)
  892. def __request_data_update(self, var_name: str, payload: t.Any) -> None:
  893. # Use custom attrgetter function to allow value binding for _MapDict
  894. newvalue = _getscopeattr_drill(self, var_name)
  895. if isinstance(newvalue, _TaipyData):
  896. ret_payload = None
  897. if isinstance(payload, dict):
  898. lib_name = payload.get("library")
  899. if isinstance(lib_name, str):
  900. libs = self.__extensions.get(lib_name, [])
  901. for lib in libs:
  902. user_var_name = var_name
  903. try:
  904. with contextlib.suppress(NameError):
  905. # ignore name error and keep var_name
  906. user_var_name = self._get_real_var_name(var_name)[0]
  907. ret_payload = lib.get_data(lib_name, payload, user_var_name, newvalue)
  908. if ret_payload:
  909. break
  910. except Exception as e: # pragma: no cover
  911. _warn(
  912. f"Exception raised in '{lib_name}.get_data({lib_name}, payload, {user_var_name}, value)'", # noqa: E501
  913. e,
  914. )
  915. if not isinstance(ret_payload, dict):
  916. ret_payload = self._accessors._get_data(self, var_name, newvalue, payload)
  917. self.__send_ws_update_with_dict({var_name: ret_payload})
  918. def __request_var_update(self, payload: t.Any):
  919. if isinstance(payload, dict) and isinstance(payload.get("names"), list):
  920. if payload.get("refresh", False):
  921. # refresh vars
  922. for _var in t.cast(list, payload.get("names")):
  923. val = _getscopeattr_drill(self, _var)
  924. self._refresh_expr(
  925. val.get_name() if isinstance(val, _TaipyBase) else _var,
  926. val if isinstance(val, _TaipyBase) else None,
  927. )
  928. self.__send_var_list_update(payload["names"])
  929. def __send_ws(self, payload: dict, allow_grouping=True) -> None:
  930. grouping_message = self.__get_message_grouping() if allow_grouping else None
  931. if grouping_message is None:
  932. try:
  933. self._server._ws.emit(
  934. "message",
  935. payload,
  936. to=self.__get_ws_receiver(),
  937. )
  938. time.sleep(0.001)
  939. except Exception as e: # pragma: no cover
  940. _warn(f"Exception raised in WebSocket communication in '{self.__frame.f_code.co_name}'", e)
  941. else:
  942. grouping_message.append(payload)
  943. def __broadcast_ws(self, payload: dict):
  944. try:
  945. self._server._ws.emit(
  946. "message",
  947. payload,
  948. )
  949. time.sleep(0.001)
  950. except Exception as e: # pragma: no cover
  951. _warn(f"Exception raised in WebSocket communication in '{self.__frame.f_code.co_name}'", e)
  952. def __send_ack(self, ack_id: t.Optional[str]) -> None:
  953. if ack_id:
  954. try:
  955. self._server._ws.emit("message", {"type": _WsType.ACKNOWLEDGEMENT.value, "id": ack_id})
  956. time.sleep(0.001)
  957. except Exception as e: # pragma: no cover
  958. _warn(f"Exception raised in WebSocket communication (send ack) in '{self.__frame.f_code.co_name}'", e)
  959. def _send_ws_id(self, id: str) -> None:
  960. self.__send_ws(
  961. {
  962. "type": _WsType.CLIENT_ID.value,
  963. "id": id,
  964. },
  965. allow_grouping=False,
  966. )
  967. def __send_ws_download(self, content: str, name: str, on_action: str) -> None:
  968. self.__send_ws({"type": _WsType.DOWNLOAD_FILE.value, "content": content, "name": name, "onAction": on_action})
  969. def __send_ws_alert(self, type: str, message: str, system_notification: bool, duration: int) -> None:
  970. self.__send_ws(
  971. {
  972. "type": _WsType.ALERT.value,
  973. "atype": type,
  974. "message": message,
  975. "system": system_notification,
  976. "duration": duration,
  977. }
  978. )
  979. def __send_ws_partial(self, partial: str):
  980. self.__send_ws(
  981. {
  982. "type": _WsType.PARTIAL.value,
  983. "name": partial,
  984. }
  985. )
  986. def __send_ws_block(
  987. self,
  988. action: t.Optional[str] = None,
  989. message: t.Optional[str] = None,
  990. close: t.Optional[bool] = False,
  991. cancel: t.Optional[bool] = False,
  992. ):
  993. self.__send_ws(
  994. {
  995. "type": _WsType.BLOCK.value,
  996. "action": action,
  997. "close": close,
  998. "message": message,
  999. "noCancel": not cancel,
  1000. }
  1001. )
  1002. def __send_ws_navigate(
  1003. self,
  1004. to: str,
  1005. params: t.Optional[t.Dict[str, str]],
  1006. tab: t.Optional[str],
  1007. force: bool,
  1008. ):
  1009. self.__send_ws({"type": _WsType.NAVIGATE.value, "to": to, "params": params, "tab": tab, "force": force})
  1010. def __send_ws_update_with_dict(self, modified_values: dict) -> None:
  1011. payload = [
  1012. {"name": _get_client_var_name(k), "payload": (v if isinstance(v, dict) and "value" in v else {"value": v})}
  1013. for k, v in modified_values.items()
  1014. ]
  1015. if self._is_broadcasting():
  1016. self.__broadcast_ws({"type": _WsType.MULTIPLE_UPDATE.value, "payload": payload})
  1017. self._set_broadcast(False)
  1018. else:
  1019. self.__send_ws({"type": _WsType.MULTIPLE_UPDATE.value, "payload": payload})
  1020. def __send_ws_broadcast(self, var_name: str, var_value: t.Any):
  1021. self.__broadcast_ws(
  1022. {"type": _WsType.UPDATE.value, "name": _get_broadcast_var_name(var_name), "payload": {"value": var_value}}
  1023. )
  1024. def __get_ws_receiver(self) -> t.Union[t.List[str], t.Any, None]:
  1025. if self._bindings()._is_single_client():
  1026. return None
  1027. sid = getattr(request, "sid", None) if request else None
  1028. sids = self.__client_id_2_sid.get(self._get_client_id(), set())
  1029. if sid:
  1030. sids.add(sid)
  1031. return list(sids)
  1032. def __get_message_grouping(self):
  1033. return (
  1034. _getscopeattr(self, Gui.__MESSAGE_GROUPING_NAME)
  1035. if _hasscopeattr(self, Gui.__MESSAGE_GROUPING_NAME)
  1036. else None
  1037. )
  1038. def __enter__(self):
  1039. self.__hold_messages()
  1040. return self
  1041. def __exit__(self, exc_type, exc_value, traceback):
  1042. try:
  1043. self.__send_messages()
  1044. except Exception as e: # pragma: no cover
  1045. _warn("Exception raised while sending messages", e)
  1046. if exc_value: # pragma: no cover
  1047. _warn(f"An {exc_type or 'Exception'} was raised", exc_value)
  1048. return True
  1049. def __hold_messages(self):
  1050. grouping_message = self.__get_message_grouping()
  1051. if grouping_message is None:
  1052. self._bind_var_val(Gui.__MESSAGE_GROUPING_NAME, [])
  1053. def __send_messages(self):
  1054. grouping_message = self.__get_message_grouping()
  1055. if grouping_message is not None:
  1056. _delscopeattr(self, Gui.__MESSAGE_GROUPING_NAME)
  1057. if len(grouping_message):
  1058. self.__send_ws({"type": _WsType.MULTIPLE_MESSAGE.value, "payload": grouping_message})
  1059. def _get_user_function(self, func_name: str) -> t.Union[t.Callable, str]:
  1060. func = _getscopeattr(self, func_name, None)
  1061. if not callable(func):
  1062. func = self._get_locals_bind().get(func_name)
  1063. if not callable(func):
  1064. func = self.__locals_context.get_default().get(func_name)
  1065. return func if callable(func) else func_name
  1066. def _get_user_instance(self, class_name: str, class_type: type) -> t.Union[object, str]:
  1067. cls = _getscopeattr(self, class_name, None)
  1068. if not isinstance(cls, class_type):
  1069. cls = self._get_locals_bind().get(class_name)
  1070. if not isinstance(cls, class_type):
  1071. cls = self.__locals_context.get_default().get(class_name)
  1072. return cls if isinstance(cls, class_type) else class_name
  1073. def __on_action(self, id: t.Optional[str], payload: t.Any) -> None:
  1074. if isinstance(payload, dict):
  1075. action = payload.get("action")
  1076. else:
  1077. action = str(payload)
  1078. payload = {"action": action}
  1079. if action:
  1080. if self.__call_function_with_args(action_function=self._get_user_function(action), id=id, payload=payload):
  1081. return
  1082. else: # pragma: no cover
  1083. _warn(f"on_action(): '{action}' is not a valid function.")
  1084. if hasattr(self, "on_action"):
  1085. self.__call_function_with_args(action_function=self.on_action, id=id, payload=payload)
  1086. def __call_function_with_args(self, **kwargs):
  1087. action_function = kwargs.get("action_function")
  1088. id = kwargs.get("id")
  1089. payload = kwargs.get("payload")
  1090. if callable(action_function):
  1091. try:
  1092. argcount = action_function.__code__.co_argcount
  1093. if argcount > 0 and inspect.ismethod(action_function):
  1094. argcount -= 1
  1095. args = [None for _ in range(argcount)]
  1096. if argcount > 0:
  1097. args[0] = self.__get_state()
  1098. if argcount > 1:
  1099. try:
  1100. args[1] = self._get_real_var_name(id)[0]
  1101. except Exception:
  1102. args[1] = id
  1103. if argcount > 2:
  1104. args[2] = payload
  1105. action_function(*args)
  1106. return True
  1107. except Exception as e: # pragma: no cover
  1108. if not self._call_on_exception(action_function.__name__, e):
  1109. _warn(f"on_action(): Exception raised in '{action_function.__name__}()'", e)
  1110. return False
  1111. def _call_function_with_state(self, user_function: t.Callable, args: t.List[t.Any]) -> t.Any:
  1112. args.insert(0, self.__get_state())
  1113. argcount = user_function.__code__.co_argcount
  1114. if argcount > 0 and inspect.ismethod(user_function):
  1115. argcount -= 1
  1116. if argcount > len(args):
  1117. args += (argcount - len(args)) * [None]
  1118. else:
  1119. args = args[:argcount]
  1120. return user_function(*args)
  1121. def _set_module_context(self, module_context: t.Optional[str]) -> t.ContextManager[None]:
  1122. return self._set_locals_context(module_context) if module_context is not None else contextlib.nullcontext()
  1123. def _call_user_callback(
  1124. self, state_id: t.Optional[str], user_callback: t.Callable, args: t.List[t.Any], module_context: t.Optional[str]
  1125. ) -> t.Any:
  1126. try:
  1127. with self.get_flask_app().app_context():
  1128. self.__set_client_id_in_context(state_id)
  1129. with self._set_module_context(module_context):
  1130. return self._call_function_with_state(user_callback, args)
  1131. except Exception as e: # pragma: no cover
  1132. if not self._call_on_exception(user_callback.__name__, e):
  1133. _warn(f"invoke_callback(): Exception raised in '{user_callback.__name__}()'", e)
  1134. return None
  1135. def _call_broadcast_callback(
  1136. self, user_callback: t.Callable, args: t.List[t.Any], module_context: t.Optional[str]
  1137. ) -> t.Any:
  1138. @contextlib.contextmanager
  1139. def _broadcast_callback() -> t.Iterator[None]:
  1140. try:
  1141. setattr(g, Gui.__BRDCST_CALLBACK_G_ID, True)
  1142. yield
  1143. finally:
  1144. setattr(g, Gui.__BRDCST_CALLBACK_G_ID, False)
  1145. with _broadcast_callback():
  1146. # Use global scopes for broadcast callbacks
  1147. return self._call_user_callback(_DataScopes._GLOBAL_ID, user_callback, args, module_context)
  1148. def _is_in_brdcst_callback(self):
  1149. try:
  1150. return getattr(g, Gui.__BRDCST_CALLBACK_G_ID, False)
  1151. except RuntimeError:
  1152. return False
  1153. # Proxy methods for Evaluator
  1154. def _evaluate_expr(self, expr: str) -> t.Any:
  1155. return self.__evaluator.evaluate_expr(self, expr)
  1156. def _re_evaluate_expr(self, var_name: str) -> t.Set[str]:
  1157. return self.__evaluator.re_evaluate_expr(self, var_name)
  1158. def _refresh_expr(self, var_name: str, holder: t.Optional[_TaipyBase]):
  1159. return self.__evaluator.refresh_expr(self, var_name, holder)
  1160. def _get_expr_from_hash(self, hash_val: str) -> str:
  1161. return self.__evaluator.get_expr_from_hash(hash_val)
  1162. def _evaluate_bind_holder(self, holder: t.Type[_TaipyBase], expr: str) -> str:
  1163. return self.__evaluator.evaluate_bind_holder(self, holder, expr)
  1164. def _evaluate_holders(self, expr: str) -> t.List[str]:
  1165. return self.__evaluator.evaluate_holders(self, expr)
  1166. def _is_expression(self, expr: str) -> bool:
  1167. if self.__evaluator is None:
  1168. return False
  1169. return self.__evaluator._is_expression(expr)
  1170. # make components resettable
  1171. def _set_building(self, building: bool):
  1172. self._building = building
  1173. def __is_building(self):
  1174. return hasattr(self, "_building") and self._building
  1175. def _get_rebuild_fn_name(self, name: str):
  1176. return f"{Gui.__SELF_VAR}.{name}"
  1177. def __get_attributes(self, attr_json: str, hash_json: str, args_dict: t.Dict[str, t.Any]):
  1178. attributes: t.Dict[str, t.Any] = json.loads(unquote(attr_json))
  1179. hashes: t.Dict[str, str] = json.loads(unquote(hash_json))
  1180. attributes.update({k: args_dict.get(v) for k, v in hashes.items()})
  1181. return attributes, hashes
  1182. def _tbl_cols(
  1183. self, rebuild: bool, rebuild_val: t.Optional[bool], attr_json: str, hash_json: str, **kwargs
  1184. ) -> t.Union[str, _DoNotUpdate]:
  1185. if not self.__is_building():
  1186. try:
  1187. rebuild = rebuild_val if rebuild_val is not None else rebuild
  1188. if rebuild:
  1189. attributes, hashes = self.__get_attributes(attr_json, hash_json, kwargs)
  1190. data_hash = hashes.get("data", "")
  1191. data = kwargs.get(data_hash)
  1192. col_dict = _get_columns_dict(
  1193. data,
  1194. attributes.get("columns", {}),
  1195. self._accessors._get_col_types(data_hash, _TaipyData(data, data_hash)),
  1196. attributes.get("date_format"),
  1197. attributes.get("number_format"),
  1198. )
  1199. _enhance_columns(attributes, hashes, col_dict, "table(cols)")
  1200. return json.dumps(col_dict, cls=_TaipyJsonEncoder)
  1201. except Exception as e: # pragma: no cover
  1202. _warn("Exception while rebuilding table columns", e)
  1203. return Gui.__DO_NOT_UPDATE_VALUE
  1204. def _chart_conf(
  1205. self, rebuild: bool, rebuild_val: t.Optional[bool], attr_json: str, hash_json: str, **kwargs
  1206. ) -> t.Union[str, _DoNotUpdate]:
  1207. if not self.__is_building():
  1208. try:
  1209. rebuild = rebuild_val if rebuild_val is not None else rebuild
  1210. if rebuild:
  1211. attributes, hashes = self.__get_attributes(attr_json, hash_json, kwargs)
  1212. data_hash = hashes.get("data", "")
  1213. config = _build_chart_config(
  1214. self,
  1215. attributes,
  1216. self._accessors._get_col_types(data_hash, _TaipyData(kwargs.get(data_hash), data_hash)),
  1217. )
  1218. return json.dumps(config, cls=_TaipyJsonEncoder)
  1219. except Exception as e: # pragma: no cover
  1220. _warn("Exception while rebuilding chart config", e)
  1221. return Gui.__DO_NOT_UPDATE_VALUE
  1222. # Proxy methods for Adapter
  1223. def _add_adapter_for_type(self, type_name: str, adapter: t.Callable) -> None:
  1224. self.__adapter._add_for_type(type_name, adapter)
  1225. def _add_type_for_var(self, var_name: str, type_name: str) -> None:
  1226. self.__adapter._add_type_for_var(var_name, type_name)
  1227. def _get_adapter_for_type(self, type_name: str) -> t.Optional[t.Callable]:
  1228. return self.__adapter._get_for_type(type_name)
  1229. def _get_unique_type_adapter(self, type_name: str) -> str:
  1230. return self.__adapter._get_unique_type(type_name)
  1231. def _run_adapter(
  1232. self, adapter: t.Optional[t.Callable], value: t.Any, var_name: str, id_only=False
  1233. ) -> t.Union[t.Tuple[str, ...], str, None]:
  1234. return self.__adapter._run(adapter, value, var_name, id_only)
  1235. def _get_valid_adapter_result(self, value: t.Any, id_only=False) -> t.Union[t.Tuple[str, ...], str, None]:
  1236. return self.__adapter._get_valid_result(value, id_only)
  1237. def _is_ui_blocked(self):
  1238. return _getscopeattr(self, Gui.__UI_BLOCK_NAME, False)
  1239. def __get_on_cancel_block_ui(self, callback: t.Optional[str]):
  1240. def _taipy_on_cancel_block_ui(guiApp, id: t.Optional[str], payload: t.Any):
  1241. if _hasscopeattr(guiApp, Gui.__UI_BLOCK_NAME):
  1242. _setscopeattr(guiApp, Gui.__UI_BLOCK_NAME, False)
  1243. guiApp.__on_action(id, {"action": callback})
  1244. return _taipy_on_cancel_block_ui
  1245. def __add_pages_in_folder(self, folder_name: str, folder_path: str):
  1246. from ._renderers import Html, Markdown
  1247. list_of_files = os.listdir(folder_path)
  1248. for file_name in list_of_files:
  1249. if file_name.startswith("__"):
  1250. continue
  1251. if (re_match := Gui.__RE_HTML.match(file_name)) and f"{re_match.group(1)}.py" not in list_of_files:
  1252. _renderers = Html(os.path.join(folder_path, file_name), frame=None)
  1253. _renderers.modify_taipy_base_url(folder_name)
  1254. self.add_page(name=f"{folder_name}/{re_match.group(1)}", page=_renderers)
  1255. elif (re_match := Gui.__RE_MD.match(file_name)) and f"{re_match.group(1)}.py" not in list_of_files:
  1256. _renderers_md = Markdown(os.path.join(folder_path, file_name), frame=None)
  1257. self.add_page(name=f"{folder_name}/{re_match.group(1)}", page=_renderers_md)
  1258. elif re_match := Gui.__RE_PY.match(file_name):
  1259. module_name = re_match.group(1)
  1260. module_path = os.path.join(folder_name, module_name).replace(os.path.sep, ".")
  1261. try:
  1262. module = importlib.import_module(module_path)
  1263. page_instance = _get_page_from_module(module)
  1264. if page_instance is not None:
  1265. self.add_page(name=f"{folder_name}/{module_name}", page=page_instance)
  1266. except Exception as e:
  1267. _warn(f"Error while importing module '{module_path}'", e)
  1268. elif os.path.isdir(child_dir_path := os.path.join(folder_path, file_name)):
  1269. child_dir_name = f"{folder_name}/{file_name}"
  1270. self.__add_pages_in_folder(child_dir_name, child_dir_path)
  1271. # Proxy methods for LocalsContext
  1272. def _get_locals_bind(self) -> t.Dict[str, t.Any]:
  1273. return self.__locals_context.get_locals()
  1274. def _get_default_locals_bind(self) -> t.Dict[str, t.Any]:
  1275. return self.__locals_context.get_default()
  1276. def _get_locals_bind_from_context(self, context: t.Optional[str]) -> t.Dict[str, t.Any]:
  1277. return self.__locals_context._get_locals_bind_from_context(context)
  1278. def _get_locals_context(self) -> str:
  1279. current_context = self.__locals_context.get_context()
  1280. return current_context if current_context is not None else self.__default_module_name
  1281. def _set_locals_context(self, context: t.Optional[str]) -> t.ContextManager[None]:
  1282. return self.__locals_context.set_locals_context(context)
  1283. def _get_page_context(self, page_name: str) -> str | None:
  1284. if page_name not in self._config.routes:
  1285. return None
  1286. page = None
  1287. for p in self._config.pages:
  1288. if p._route == page_name:
  1289. page = p
  1290. if page is None:
  1291. return None
  1292. return (
  1293. (page._renderer._get_module_name() or self.__default_module_name)
  1294. if page._renderer is not None
  1295. else self.__default_module_name
  1296. )
  1297. @staticmethod
  1298. def _get_root_page_name():
  1299. return Gui.__root_page_name
  1300. def _set_flask(self, flask: Flask):
  1301. self._flask = flask
  1302. def _get_default_module_name(self):
  1303. return self.__default_module_name
  1304. @staticmethod
  1305. def _get_timezone() -> str:
  1306. return Gui.__LOCAL_TZ
  1307. @staticmethod
  1308. def _set_timezone(tz: str):
  1309. Gui.__LOCAL_TZ = tz
  1310. # Public methods
  1311. def add_page(
  1312. self,
  1313. name: str,
  1314. page: t.Union[str, Page],
  1315. style: t.Optional[str] = "",
  1316. ) -> None:
  1317. """Add a page to the Graphical User Interface.
  1318. Arguments:
  1319. name: The name of the page.
  1320. page (Union[str, Page^]): The content of the page.<br/>
  1321. It can be an instance of `Markdown^` or `Html^`.<br/>
  1322. If *page* is a string, then:
  1323. - If *page* is set to the pathname of a readable file, the page
  1324. content is read as Markdown input text.
  1325. - If it is not, the page content is read from this string as
  1326. Markdown text.
  1327. style (Optional[str]): Additional CSS style to apply to this page.
  1328. - if there is style associated with a page, it is used at a global level
  1329. - if there is no style associated with the page, the style is cleared at a global level
  1330. - if the page is embedded in a block control, the style is ignored
  1331. Note that page names cannot start with the slash ('/') character and that each
  1332. page must have a unique name.
  1333. """
  1334. # Validate name
  1335. if name is None: # pragma: no cover
  1336. raise Exception("name is required for add_page() function.")
  1337. if not Gui.__RE_PAGE_NAME.match(name): # pragma: no cover
  1338. raise SyntaxError(
  1339. f'Page name "{name}" is invalid. It must only contain letters, digits, dash (-), underscore (_), and forward slash (/) characters.' # noqa: E501
  1340. )
  1341. if name.startswith("/"): # pragma: no cover
  1342. raise SyntaxError(f'Page name "{name}" cannot start with forward slash (/) character.')
  1343. if name in self._config.routes: # pragma: no cover
  1344. raise Exception(f'Page name "{name if name != Gui.__root_page_name else "/"}" is already defined.')
  1345. if isinstance(page, str):
  1346. from ._renderers import Markdown
  1347. page = Markdown(page, frame=None)
  1348. elif not isinstance(page, Page): # pragma: no cover
  1349. raise Exception(
  1350. f'Parameter "page" is invalid for page name "{name if name != Gui.__root_page_name else "/"}.'
  1351. )
  1352. # Init a new page
  1353. new_page = _Page()
  1354. new_page._route = name
  1355. new_page._renderer = page
  1356. new_page._style = style
  1357. # Append page to _config
  1358. self._config.pages.append(new_page)
  1359. self._config.routes.append(name)
  1360. # set root page
  1361. if name == Gui.__root_page_name:
  1362. self._config.root_page = new_page
  1363. # Update locals context
  1364. self.__locals_context.add(page._get_module_name(), page._get_locals())
  1365. # Update variable directory
  1366. if not page._is_class_module():
  1367. self.__var_dir.add_frame(page._frame)
  1368. def add_pages(self, pages: t.Optional[t.Union[t.Mapping[str, t.Union[str, Page]], str]] = None) -> None:
  1369. """Add several pages to the Graphical User Interface.
  1370. Arguments:
  1371. pages (Union[dict[str, Union[str, Page^]], str]): The pages to add.<br/>
  1372. If *pages* is a dictionary, a page is added to this `Gui` instance
  1373. for each of the entries in *pages*:
  1374. - The entry key is used as the page name.
  1375. - The entry value is used as the page content:
  1376. - The value can can be an instance of `Markdown^` or `Html^`, then
  1377. it is used as the page definition.
  1378. - If entry value is a string, then:
  1379. - If it is set to the pathname of a readable file, the page
  1380. content is read as Markdown input text.
  1381. - If it is not, the page content is read from this string as
  1382. Markdown text.
  1383. !!! note "Reading pages from a directory"
  1384. If *pages* is a string that holds the path to a readable directory, then
  1385. this directory is traversed, recursively, to find files that Taipy can build
  1386. pages from.
  1387. For every new directory that is traversed, a new hierarchical level
  1388. for pages is created.
  1389. For every file that is found:
  1390. - If the filename extension is *.md*, it is read as Markdown content and
  1391. a new page is created with the base name of this filename.
  1392. - If the filename extension is *.html*, it is read as HTML content and
  1393. a new page is created with the base name of this filename.
  1394. For example, say you have the following directory structure:
  1395. ```
  1396. reports
  1397. ├── home.html
  1398. ├── budget/
  1399. │ ├── expenses/
  1400. │ │ ├── marketing.md
  1401. │ │ └── production.md
  1402. │ └── revenue/
  1403. │ ├── EMAE.md
  1404. │ ├── USA.md
  1405. │ └── ASIA.md
  1406. └── cashflow/
  1407. ├── weekly.md
  1408. ├── monthly.md
  1409. └── yearly.md
  1410. ```
  1411. Calling `gui.add_pages('reports')` is equivalent to calling:
  1412. ```py
  1413. gui.add_pages({
  1414. "reports/home", Html("reports/home.html"),
  1415. "reports/budget/expenses/marketing", Markdown("reports/budget/expenses/marketing.md"),
  1416. "reports/budget/expenses/production", Markdown("reports/budget/expenses/production.md"),
  1417. "reports/budget/revenue/EMAE", Markdown("reports/budget/revenue/EMAE.md"),
  1418. "reports/budget/revenue/USA", Markdown("reports/budget/revenue/USA.md"),
  1419. "reports/budget/revenue/ASIA", Markdown("reports/budget/revenue/ASIA.md"),
  1420. "reports/cashflow/weekly", Markdown("reports/cashflow/weekly.md"),
  1421. "reports/cashflow/monthly", Markdown("reports/cashflow/monthly.md"),
  1422. "reports/cashflow/yearly", Markdown("reports/cashflow/yearly.md")
  1423. })
  1424. ```
  1425. """
  1426. if isinstance(pages, dict):
  1427. for k, v in pages.items():
  1428. if k == "/":
  1429. k = Gui.__root_page_name
  1430. self.add_page(name=k, page=v)
  1431. elif isinstance(folder_name := pages, str):
  1432. if not hasattr(self, "_root_dir"):
  1433. self._root_dir = os.path.dirname(inspect.getabsfile(self.__frame))
  1434. folder_path = folder_name if os.path.isabs(folder_name) else os.path.join(self._root_dir, folder_name)
  1435. folder_name = os.path.basename(folder_path)
  1436. if not os.path.isdir(folder_path): # pragma: no cover
  1437. raise RuntimeError(f"Path {folder_path} is not a valid directory")
  1438. if folder_name in self.__directory_name_of_pages: # pragma: no cover
  1439. raise Exception(f"Base directory name {folder_name} of path {folder_path} is not unique")
  1440. if folder_name in Gui.__reserved_routes: # pragma: no cover
  1441. raise Exception(f"Invalid directory. Directory {folder_name} is a reserved route")
  1442. self.__directory_name_of_pages.append(folder_name)
  1443. self.__add_pages_in_folder(folder_name, folder_path)
  1444. # partials
  1445. def add_partial(
  1446. self,
  1447. page: t.Union[str, Page],
  1448. ) -> Partial:
  1449. """Create a new `Partial^`.
  1450. The [User Manual section on Partials](../gui/pages/index.md#partials) gives details on
  1451. when and how to use this class.
  1452. Arguments:
  1453. page (Union[str, Page^]): The page to create a new Partial from.<br/>
  1454. It can be an instance of `Markdown^` or `Html^`.<br/>
  1455. If *page* is a string, then:
  1456. - If *page* is set to the pathname of a readable file, the content of
  1457. the new `Partial` is read as Markdown input text.
  1458. - If it is not, the content of the new `Partial` is read from this string
  1459. as Markdown text.
  1460. Returns:
  1461. The new `Partial` object defined by *page*.
  1462. """
  1463. new_partial = Partial()
  1464. # Validate name
  1465. if (
  1466. new_partial._route in self._config.partial_routes or new_partial._route in self._config.routes
  1467. ): # pragma: no cover
  1468. _warn(f'Partial name "{new_partial._route}" is already defined.')
  1469. if isinstance(page, str):
  1470. from ._renderers import Markdown
  1471. page = Markdown(page, frame=None)
  1472. elif not isinstance(page, Page): # pragma: no cover
  1473. raise Exception(f'Partial name "{new_partial._route}" has an invalid Page.')
  1474. new_partial._renderer = page
  1475. # Append partial to _config
  1476. self._config.partials.append(new_partial)
  1477. self._config.partial_routes.append(str(new_partial._route))
  1478. # Update locals context
  1479. self.__locals_context.add(page._get_module_name(), page._get_locals())
  1480. # Update variable directory
  1481. self.__var_dir.add_frame(page._frame)
  1482. return new_partial
  1483. def _update_partial(self, partial: Partial):
  1484. partials = _getscopeattr(self, Partial._PARTIALS, {})
  1485. partials[partial._route] = partial
  1486. _setscopeattr(self, Partial._PARTIALS, partials)
  1487. self.__send_ws_partial(str(partial._route))
  1488. def _get_partial(self, route: str) -> t.Optional[Partial]:
  1489. partials = _getscopeattr(self, Partial._PARTIALS, {})
  1490. partial = partials.get(route)
  1491. if partial is None:
  1492. partial = next((p for p in self._config.partials if p._route == route), None)
  1493. return partial
  1494. # Main binding method (bind in markdown declaration)
  1495. def _bind_var(self, var_name: str) -> str:
  1496. bind_context = None
  1497. if var_name in self._get_locals_bind().keys():
  1498. bind_context = self._get_locals_context()
  1499. if bind_context is None:
  1500. encoded_var_name = self.__var_dir.add_var(var_name, self._get_locals_context(), var_name)
  1501. else:
  1502. encoded_var_name = self.__var_dir.add_var(var_name, bind_context)
  1503. if not hasattr(self._bindings(), encoded_var_name):
  1504. bind_locals = self._get_locals_bind_from_context(bind_context)
  1505. if var_name in bind_locals.keys():
  1506. self._bind(encoded_var_name, bind_locals[var_name])
  1507. else:
  1508. _warn(
  1509. f"Variable '{var_name}' is not available in either the '{self._get_locals_context()}' or '__main__' modules." # noqa: E501
  1510. )
  1511. return encoded_var_name
  1512. def _bind_var_val(self, var_name: str, value: t.Any) -> bool:
  1513. if _MODULE_ID not in var_name:
  1514. var_name = self.__var_dir.add_var(var_name, self._get_locals_context())
  1515. if not hasattr(self._bindings(), var_name):
  1516. self._bind(var_name, value)
  1517. return True
  1518. return False
  1519. def __bind_local_func(self, name: str):
  1520. func = getattr(self, name, None)
  1521. if func is not None and not callable(func): # pragma: no cover
  1522. _warn(f"{self.__class__.__name__}.{name}: {func} should be a function; looking for {name} in the script.")
  1523. func = None
  1524. if func is None:
  1525. func = self._get_locals_bind().get(name)
  1526. if func is not None:
  1527. if callable(func):
  1528. setattr(self, name, func)
  1529. else: # pragma: no cover
  1530. _warn(f"{name}: {func} should be a function.")
  1531. def load_config(self, config: Config) -> None:
  1532. self._config._load(config)
  1533. def _broadcast(self, name: str, value: t.Any):
  1534. """NOT UNDOCUMENTED
  1535. Send the new value of a variable to all connected clients.
  1536. Arguments:
  1537. name: The name of the variable to update or create.
  1538. value: The value (must be serializable to the JSON format).
  1539. """
  1540. self.__send_ws_broadcast(name, value)
  1541. def _broadcast_all_clients(self, name: str, value: t.Any):
  1542. try:
  1543. self._set_broadcast()
  1544. self._update_var(name, value)
  1545. finally:
  1546. self._set_broadcast(False)
  1547. def _set_broadcast(self, broadcast: bool = True):
  1548. with contextlib.suppress(RuntimeError):
  1549. setattr(g, Gui.__BROADCAST_G_ID, broadcast)
  1550. def _is_broadcasting(self) -> bool:
  1551. try:
  1552. return getattr(g, Gui.__BROADCAST_G_ID, False)
  1553. except RuntimeError:
  1554. return False
  1555. def _download(
  1556. self, content: t.Any, name: t.Optional[str] = "", on_action: t.Optional[t.Union[str, t.Callable]] = ""
  1557. ):
  1558. if callable(on_action) and on_action.__name__:
  1559. on_action_name = (
  1560. _get_expr_var_name(str(on_action.__code__))
  1561. if on_action.__name__ == "<lambda>"
  1562. else _get_expr_var_name(on_action.__name__)
  1563. )
  1564. if on_action_name:
  1565. self._bind_var_val(on_action_name, on_action)
  1566. on_action = on_action_name
  1567. else:
  1568. _warn("download() on_action is invalid.")
  1569. content_str = self._get_content("Gui.download", content, False)
  1570. self.__send_ws_download(content_str, str(name), str(on_action))
  1571. def _notify(
  1572. self,
  1573. notification_type: str = "I",
  1574. message: str = "",
  1575. system_notification: t.Optional[bool] = None,
  1576. duration: t.Optional[int] = None,
  1577. ):
  1578. self.__send_ws_alert(
  1579. notification_type,
  1580. message,
  1581. self._get_config("system_notification", False) if system_notification is None else system_notification,
  1582. self._get_config("notification_duration", 3000) if duration is None else duration,
  1583. )
  1584. def _hold_actions(
  1585. self,
  1586. callback: t.Optional[t.Union[str, t.Callable]] = None,
  1587. message: t.Optional[str] = "Work in Progress...",
  1588. ): # pragma: no cover
  1589. action_name = callback.__name__ if callable(callback) else callback
  1590. # TODO: what if lambda? (it does work)
  1591. func = self.__get_on_cancel_block_ui(action_name)
  1592. def_action_name = func.__name__
  1593. _setscopeattr(self, def_action_name, func)
  1594. if _hasscopeattr(self, Gui.__UI_BLOCK_NAME):
  1595. _setscopeattr(self, Gui.__UI_BLOCK_NAME, True)
  1596. else:
  1597. self._bind(Gui.__UI_BLOCK_NAME, True)
  1598. self.__send_ws_block(action=def_action_name, message=message, cancel=bool(action_name))
  1599. def _resume_actions(self): # pragma: no cover
  1600. if _hasscopeattr(self, Gui.__UI_BLOCK_NAME):
  1601. _setscopeattr(self, Gui.__UI_BLOCK_NAME, False)
  1602. self.__send_ws_block(close=True)
  1603. def _navigate(
  1604. self,
  1605. to: t.Optional[str] = "",
  1606. params: t.Optional[t.Dict[str, str]] = None,
  1607. tab: t.Optional[str] = None,
  1608. force: t.Optional[bool] = False,
  1609. ):
  1610. to = to or Gui.__root_page_name
  1611. if not to.startswith("/") and to not in self._config.routes and not urlparse(to).netloc:
  1612. _warn(f'Cannot navigate to "{to if to != Gui.__root_page_name else "/"}": unknown page.')
  1613. return False
  1614. self.__send_ws_navigate(to if to != Gui.__root_page_name else "/", params, tab, force or False)
  1615. return True
  1616. def __init_libs(self):
  1617. for name, libs in self.__extensions.items():
  1618. for lib in libs:
  1619. if not isinstance(lib, ElementLibrary):
  1620. continue
  1621. try:
  1622. self._call_function_with_state(lib.on_user_init, [])
  1623. except Exception as e: # pragma: no cover
  1624. if not self._call_on_exception(f"{name}.on_user_init", e):
  1625. _warn(f"Exception raised in {name}.on_user_init()", e)
  1626. def __init_route(self):
  1627. self.__set_client_id_in_context(force=True)
  1628. if not _hasscopeattr(self, Gui.__ON_INIT_NAME):
  1629. _setscopeattr(self, Gui.__ON_INIT_NAME, True)
  1630. self.__pre_render_pages()
  1631. self.__init_libs()
  1632. if hasattr(self, "on_init") and callable(self.on_init):
  1633. try:
  1634. self._call_function_with_state(self.on_init, [])
  1635. except Exception as e: # pragma: no cover
  1636. if not self._call_on_exception("on_init", e):
  1637. _warn("Exception raised in on_init()", e)
  1638. return self._render_route()
  1639. def _call_on_exception(self, function_name: str, exception: Exception) -> bool:
  1640. if hasattr(self, "on_exception") and callable(self.on_exception):
  1641. try:
  1642. self.on_exception(self.__get_state(), str(function_name), exception)
  1643. except Exception as e: # pragma: no cover
  1644. _warn("Exception raised in on_exception()", e)
  1645. return True
  1646. return False
  1647. def __call_on_status(self) -> t.Optional[str]:
  1648. if hasattr(self, "on_status") and callable(self.on_status):
  1649. try:
  1650. return self.on_status(self.__get_state())
  1651. except Exception as e: # pragma: no cover
  1652. if not self._call_on_exception("on_status", e):
  1653. _warn("Exception raised in on_status", e)
  1654. return None
  1655. def __pre_render_pages(self) -> None:
  1656. """Pre-render all pages to have a proper initialization of all variables"""
  1657. self.__set_client_id_in_context()
  1658. for page in self._config.pages:
  1659. if page is not None:
  1660. with contextlib.suppress(Exception):
  1661. page.render(self)
  1662. def __render_page(self, page_name: str) -> t.Any:
  1663. self.__set_client_id_in_context()
  1664. nav_page = page_name
  1665. if hasattr(self, "on_navigate") and callable(self.on_navigate):
  1666. try:
  1667. if self.on_navigate.__code__.co_argcount == 2:
  1668. nav_page = self.on_navigate(self.__get_state(), page_name)
  1669. else:
  1670. params = request.args.to_dict() if hasattr(request, "args") else {}
  1671. params.pop("client_id", None)
  1672. params.pop("v", None)
  1673. nav_page = self.on_navigate(self.__get_state(), page_name, params)
  1674. if nav_page != page_name:
  1675. if isinstance(nav_page, str):
  1676. if self._navigate(nav_page):
  1677. return ("Root page cannot be re-routed by on_navigate().", 302)
  1678. else:
  1679. _warn(f"on_navigate() returned an invalid page name '{nav_page}'.")
  1680. nav_page = page_name
  1681. except Exception as e: # pragma: no cover
  1682. if not self._call_on_exception("on_navigate", e):
  1683. _warn("Exception raised in on_navigate()", e)
  1684. page = next((page_i for page_i in self._config.pages if page_i._route == nav_page), None)
  1685. # Try partials
  1686. if page is None:
  1687. page = self._get_partial(nav_page)
  1688. # Make sure that there is a page instance found
  1689. if page is None:
  1690. return (
  1691. jsonify({"error": f"Page '{nav_page}' doesn't exist."}),
  1692. 400,
  1693. {"Content-Type": "application/json; charset=utf-8"},
  1694. )
  1695. context = page.render(self)
  1696. if (
  1697. nav_page == Gui.__root_page_name
  1698. and page._rendered_jsx is not None
  1699. and "<PageContent" not in page._rendered_jsx
  1700. ):
  1701. page._rendered_jsx += "<PageContent />"
  1702. # Return jsx page
  1703. if page._rendered_jsx is not None:
  1704. return self._server._render(
  1705. page._rendered_jsx, page._style if page._style is not None else "", page._head, context
  1706. )
  1707. else:
  1708. return ("No page template", 404)
  1709. def _render_route(self) -> t.Any:
  1710. return self._server._direct_render_json(
  1711. {
  1712. "locations": {
  1713. "/" if route == Gui.__root_page_name else f"/{route}": f"/{route}" for route in self._config.routes
  1714. },
  1715. "blockUI": self._is_ui_blocked(),
  1716. }
  1717. )
  1718. def _register_data_accessor(self, data_accessor_class: t.Type[_DataAccessor]) -> None:
  1719. self._accessors._register(data_accessor_class)
  1720. def get_flask_app(self) -> Flask:
  1721. """Get the internal Flask application.
  1722. This method must be called **after** `(Gui.)run()^` was invoked.
  1723. Returns:
  1724. The Flask instance used.
  1725. """
  1726. if hasattr(self, "_server"):
  1727. return self._server.get_flask()
  1728. raise RuntimeError("get_flask_app() cannot be invoked before run() has been called.")
  1729. def _set_frame(self, frame: FrameType):
  1730. if not isinstance(frame, FrameType): # pragma: no cover
  1731. raise RuntimeError("frame must be a FrameType where Gui can collect the local variables.")
  1732. self.__frame = frame
  1733. self.__default_module_name = _get_module_name_from_frame(self.__frame)
  1734. def _set_css_file(self, css_file: t.Optional[str] = None):
  1735. if css_file is None:
  1736. script_file = pathlib.Path(self.__frame.f_code.co_filename or ".").resolve()
  1737. if script_file.with_suffix(".css").exists():
  1738. css_file = f"{script_file.stem}.css"
  1739. elif script_file.is_dir() and (script_file / "taipy.css").exists():
  1740. css_file = "taipy.css"
  1741. self.__css_file = css_file
  1742. def _set_state(self, state: State):
  1743. if isinstance(state, State):
  1744. self.__state = state
  1745. def __get_client_config(self) -> t.Dict[str, t.Any]:
  1746. config = {
  1747. "timeZone": self._config.get_time_zone(),
  1748. "darkMode": self._get_config("dark_mode", True),
  1749. "baseURL": self._config._get_config("base_url", "/"),
  1750. }
  1751. if themes := self._get_themes():
  1752. config["themes"] = themes
  1753. if len(self.__extensions):
  1754. config["extensions"] = {}
  1755. for libs in self.__extensions.values():
  1756. for lib in libs:
  1757. config["extensions"][f"./{Gui._EXTENSION_ROOT}/{lib.get_js_module_name()}"] = [ # type: ignore
  1758. e._get_js_name(n)
  1759. for n, e in lib.get_elements().items()
  1760. if isinstance(e, Element) and not e._is_server_only()
  1761. ]
  1762. if stylekit := self._get_config("stylekit", _default_stylekit):
  1763. config["stylekit"] = {_to_camel_case(k): v for k, v in stylekit.items()}
  1764. return config
  1765. def __get_css_vars(self) -> str:
  1766. css_vars = []
  1767. if stylekit := self._get_config("stylekit", _default_stylekit):
  1768. for k, v in stylekit.items():
  1769. css_vars.append(f'--{k.replace("_", "-")}:{_get_css_var_value(v)};')
  1770. return " ".join(css_vars)
  1771. def __init_server(self):
  1772. app_config = self._config.config
  1773. # Init server if there is no server
  1774. if not hasattr(self, "_server"):
  1775. self._server = _Server(
  1776. self,
  1777. path_mapping=self._path_mapping,
  1778. flask=self._flask,
  1779. async_mode=app_config["async_mode"],
  1780. allow_upgrades=not app_config["notebook_proxy"],
  1781. server_config=app_config.get("server_config"),
  1782. )
  1783. # Stop and reinitialize the server if it is still running as a thread
  1784. if (_is_in_notebook() or app_config["run_in_thread"]) and hasattr(self._server, "_thread"):
  1785. self.stop()
  1786. self._flask_blueprint = []
  1787. self._server = _Server(
  1788. self,
  1789. path_mapping=self._path_mapping,
  1790. flask=self._flask,
  1791. async_mode=app_config["async_mode"],
  1792. allow_upgrades=not app_config["notebook_proxy"],
  1793. server_config=app_config.get("server_config"),
  1794. )
  1795. self._bindings()._new_scopes()
  1796. def __init_ngrok(self):
  1797. app_config = self._config.config
  1798. if app_config["run_server"] and app_config["ngrok_token"]: # pragma: no cover
  1799. if not util.find_spec("pyngrok"):
  1800. raise RuntimeError("Cannot use ngrok as pyngrok package is not installed.")
  1801. ngrok.set_auth_token(app_config["ngrok_token"])
  1802. http_tunnel = ngrok.connect(app_config["port"], "http")
  1803. _TaipyLogger._get_logger().info(f" * NGROK Public Url: {http_tunnel.public_url}")
  1804. def __bind_default_function(self):
  1805. with self.get_flask_app().app_context():
  1806. self.__var_dir.process_imported_var()
  1807. # bind on_* function if available
  1808. self.__bind_local_func("on_init")
  1809. self.__bind_local_func("on_change")
  1810. self.__bind_local_func("on_action")
  1811. self.__bind_local_func("on_navigate")
  1812. self.__bind_local_func("on_exception")
  1813. self.__bind_local_func("on_status")
  1814. self.__bind_local_func("on_user_content")
  1815. def __register_blueprint(self):
  1816. # add en empty main page if it is not defined
  1817. if Gui.__root_page_name not in self._config.routes:
  1818. new_page = _Page()
  1819. new_page._route = Gui.__root_page_name
  1820. new_page._renderer = _EmptyPage()
  1821. self._config.pages.append(new_page)
  1822. self._config.routes.append(Gui.__root_page_name)
  1823. pages_bp = Blueprint("taipy_pages", __name__)
  1824. self._flask_blueprint.append(pages_bp)
  1825. # server URL Rule for taipy images
  1826. images_bp = Blueprint("taipy_images", __name__)
  1827. images_bp.add_url_rule(f"/{Gui.__CONTENT_ROOT}/<path:path>", view_func=self.__serve_content)
  1828. self._flask_blueprint.append(images_bp)
  1829. # server URL for uploaded files
  1830. upload_bp = Blueprint("taipy_upload", __name__)
  1831. upload_bp.add_url_rule(f"/{Gui.__UPLOAD_URL}", view_func=self.__upload_files, methods=["POST"])
  1832. self._flask_blueprint.append(upload_bp)
  1833. # server URL for user content
  1834. user_content_bp = Blueprint("taipy_user_content", __name__)
  1835. user_content_bp.add_url_rule(f"/{Gui.__USER_CONTENT_URL}/<path:path>", view_func=self.__serve_user_content)
  1836. self._flask_blueprint.append(user_content_bp)
  1837. # server URL for extension resources
  1838. extension_bp = Blueprint("taipy_extensions", __name__)
  1839. extension_bp.add_url_rule(f"/{Gui._EXTENSION_ROOT}/<path:path>", view_func=self.__serve_extension)
  1840. scripts = [
  1841. s if bool(urlparse(s).netloc) else f"/{Gui._EXTENSION_ROOT}/{name}/{s}{lib.get_query(s)}"
  1842. for name, libs in Gui.__extensions.items()
  1843. for lib in libs
  1844. for s in (lib.get_scripts() or [])
  1845. ]
  1846. styles = [
  1847. s if bool(urlparse(s).netloc) else f"/{Gui._EXTENSION_ROOT}/{name}/{s}{lib.get_query(s)}"
  1848. for name, libs in Gui.__extensions.items()
  1849. for lib in libs
  1850. for s in (lib.get_styles() or [])
  1851. ]
  1852. if self._get_config("stylekit", True):
  1853. styles.append("stylekit/stylekit.css")
  1854. else:
  1855. styles.append("https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap")
  1856. if self.__css_file:
  1857. styles.append(f"/{self.__css_file}")
  1858. self._flask_blueprint.append(extension_bp)
  1859. _conf_webapp_path = (
  1860. pathlib.Path(self._get_config("webapp_path", None)) if self._get_config("webapp_path", None) else None
  1861. )
  1862. _webapp_path = str((pathlib.Path(__file__).parent / "webapp").resolve())
  1863. if _conf_webapp_path:
  1864. if _conf_webapp_path.is_dir():
  1865. _webapp_path = str(_conf_webapp_path.resolve())
  1866. _warn(f"Using webapp_path: '{_conf_webapp_path}'.")
  1867. else: # pragma: no cover
  1868. _warn(
  1869. f"webapp_path: '{_conf_webapp_path}' is not a valid directory path. Falling back to '{_webapp_path}'." # noqa: E501
  1870. )
  1871. self._flask_blueprint.append(
  1872. self._server._get_default_blueprint(
  1873. static_folder=_webapp_path,
  1874. template_folder=_webapp_path,
  1875. title=self._get_config("title", "Taipy App"),
  1876. favicon=self._get_config("favicon", "favicon.png"),
  1877. root_margin=self._get_config("margin", None),
  1878. scripts=scripts,
  1879. styles=styles,
  1880. version=self.__get_version(),
  1881. client_config=self.__get_client_config(),
  1882. watermark=self._get_config("watermark", None),
  1883. css_vars=self.__get_css_vars(),
  1884. base_url=self._get_config("base_url", "/"),
  1885. )
  1886. )
  1887. # Run parse markdown to force variables binding at runtime
  1888. pages_bp.add_url_rule(f"/{Gui.__JSX_URL}/<path:page_name>", view_func=self.__render_page)
  1889. # server URL Rule for flask rendered react-router
  1890. pages_bp.add_url_rule(f"/{Gui.__INIT_URL}", view_func=self.__init_route)
  1891. # Register Flask Blueprint if available
  1892. for bp in self._flask_blueprint:
  1893. self._server.get_flask().register_blueprint(bp)
  1894. def run(
  1895. self,
  1896. run_server: bool = True,
  1897. run_in_thread: bool = False,
  1898. async_mode: str = "gevent",
  1899. **kwargs,
  1900. ) -> t.Optional[Flask]:
  1901. """
  1902. Start the server that delivers pages to web clients.
  1903. Once you enter `run()`, users can run web browsers and point to the web server
  1904. URL that `Gui` serves. The default is to listen to the *localhost* address
  1905. (127.0.0.1) on the port number 5000. However, the configuration of this `Gui`
  1906. object may impact that (see the
  1907. [Configuration](../gui/configuration.md#configuring-the-gui-instance)
  1908. section of the User Manual for details).
  1909. Arguments:
  1910. run_server (bool): Whether or not to run a web server locally.
  1911. If set to *False*, a web server is *not* created and started.
  1912. run_in_thread (bool): Whether or not to run a web server in a separated thread.
  1913. If set to *True*, the web server runs is a separated thread.<br/>
  1914. Note that if you are running in an IPython notebook context, the web
  1915. server always runs in a separate thread.
  1916. async_mode (str): The asynchronous model to use for the Flask-SocketIO.
  1917. Valid values are:<br/>
  1918. - "gevent": Use a [gevent](https://www.gevent.org/servers.html) server.
  1919. - "threading": Use the Flask Development Server. This allows the application to use
  1920. the Flask reloader (the *use_reloader* option) and Debug mode (the *debug* option).
  1921. - "eventlet": Use an [*eventlet*](https://flask.palletsprojects.com/en/2.2.x/deploying/eventlet/)
  1922. event-driven WSGI server.
  1923. The default value is "gevent"<br/>
  1924. Note that only the "threading" value provides support for the development reloader
  1925. functionality (*use_reloader* option). Any other value makes the *use_reloader* configuration parameter
  1926. ignored.<br/>
  1927. Also note that setting the *debug* argument to True forces *async_mode* to "threading".
  1928. **kwargs (dict[str, any]): Additional keyword arguments that configure how this `Gui` is run.
  1929. Please refer to the
  1930. [Configuration section](../gui/configuration.md#configuring-the-gui-instance)
  1931. of the User Manual for more information.
  1932. Returns:
  1933. The Flask instance if *run_server* is False else None.
  1934. """
  1935. # --------------------------------------------------------------------------------
  1936. # The ssl_context argument was removed just after 1.1. It was defined as:
  1937. # t.Optional[t.Union[ssl.SSLContext, t.Tuple[str, t.Optional[str]], t.Literal["adhoc"]]] = None
  1938. #
  1939. # With the doc:
  1940. # ssl_context (Optional[Union[ssl.SSLContext, Tuple[str, Optional[str]], t.Literal['adhoc']]]):
  1941. # Configures TLS to serve over HTTPS. This value can be:
  1942. #
  1943. # - An `ssl.SSLContext` object
  1944. # - A `(cert_file, key_file)` tuple to create a typical context
  1945. # - The string "adhoc" to generate a temporary self-signed certificate.
  1946. #
  1947. # The default value is None.
  1948. # --------------------------------------------------------------------------------
  1949. app_config = self._config.config
  1950. run_root_dir = os.path.dirname(inspect.getabsfile(self.__frame))
  1951. # Register _root_dir for abs path
  1952. if not hasattr(self, "_root_dir"):
  1953. self._root_dir = run_root_dir
  1954. is_reloading = kwargs.pop("_reload", False)
  1955. if not is_reloading:
  1956. self.__run_kwargs = kwargs = {
  1957. **kwargs,
  1958. "run_server": run_server,
  1959. "run_in_thread": run_in_thread,
  1960. "async_mode": async_mode,
  1961. }
  1962. # Load application config from multiple sources (env files, kwargs, command line)
  1963. self._config._build_config(run_root_dir, self.__env_filename, kwargs)
  1964. self._config.resolve()
  1965. TaipyGuiWarning.set_debug_mode(self._get_config("debug", False))
  1966. self.__init_server()
  1967. self.__init_ngrok()
  1968. locals_bind = _filter_locals(self.__frame.f_locals)
  1969. self.__locals_context.set_default(locals_bind, self.__default_module_name)
  1970. self.__var_dir.set_default(self.__frame)
  1971. if self.__state is None or is_reloading:
  1972. self.__state = State(self, self.__locals_context.get_all_keys(), self.__locals_context.get_all_context())
  1973. if _is_in_notebook():
  1974. # Allow gui.state.x in notebook mode
  1975. self.state = self.__state
  1976. self.__bind_default_function()
  1977. # Base global ctx is TaipyHolder classes + script modules and callables
  1978. glob_ctx: t.Dict[str, t.Any] = {t.__name__: t for t in _TaipyBase.__subclasses__()}
  1979. glob_ctx.update({k: v for k, v in locals_bind.items() if inspect.ismodule(v) or callable(v)})
  1980. glob_ctx[Gui.__SELF_VAR] = self
  1981. # Call on_init on each library
  1982. for name, libs in self.__extensions.items():
  1983. for lib in libs:
  1984. if not isinstance(lib, ElementLibrary):
  1985. continue
  1986. try:
  1987. lib_context = lib.on_init(self)
  1988. if (
  1989. isinstance(lib_context, tuple)
  1990. and len(lib_context) > 1
  1991. and isinstance(lib_context[0], str)
  1992. and lib_context[0].isidentifier()
  1993. ):
  1994. if lib_context[0] in glob_ctx:
  1995. _warn(f"Method {name}.on_init() returned a name already defined '{lib_context[0]}'.")
  1996. else:
  1997. glob_ctx[lib_context[0]] = lib_context[1]
  1998. elif lib_context:
  1999. _warn(
  2000. f"Method {name}.on_init() should return a Tuple[str, Any] where the first element must be a valid Python identifier." # noqa: E501
  2001. )
  2002. except Exception as e: # pragma: no cover
  2003. if not self._call_on_exception(f"{name}.on_init", e):
  2004. _warn(f"Method {name}.on_init() raised an exception", e)
  2005. # Initiate the Evaluator with the right context
  2006. self.__evaluator = _Evaluator(glob_ctx, self.__shared_variables)
  2007. self.__register_blueprint()
  2008. # Register data accessor communication data format (JSON, Apache Arrow)
  2009. self._accessors._set_data_format(_DataFormat.APACHE_ARROW if app_config["use_arrow"] else _DataFormat.JSON)
  2010. # Use multi user or not
  2011. self._bindings()._set_single_client(bool(app_config["single_client"]))
  2012. # Start Flask Server
  2013. if not run_server:
  2014. return self.get_flask_app()
  2015. return self._server.run(
  2016. host=app_config["host"],
  2017. port=app_config["port"],
  2018. debug=app_config["debug"],
  2019. use_reloader=app_config["use_reloader"],
  2020. flask_log=app_config["flask_log"],
  2021. run_in_thread=app_config["run_in_thread"],
  2022. allow_unsafe_werkzeug=app_config["allow_unsafe_werkzeug"],
  2023. notebook_proxy=app_config["notebook_proxy"],
  2024. )
  2025. def reload(self): # pragma: no cover
  2026. """
  2027. Reload the web server.
  2028. This function reloads the underlying web server only in the situation where
  2029. it was run in a separated thread: the *run_in_thread* parameter to the
  2030. `(Gui.)run^` method was set to True, or you are running in an IPython notebook
  2031. context.
  2032. """
  2033. if hasattr(self, "_server") and hasattr(self._server, "_thread") and self._server._is_running:
  2034. self._server.stop_thread()
  2035. self.run(**self.__run_kwargs, _reload=True)
  2036. _TaipyLogger._get_logger().info("Gui server has been reloaded.")
  2037. def stop(self):
  2038. """
  2039. Stop the web server.
  2040. This function stops the underlying web server only in the situation where
  2041. it was run in a separated thread: the *run_in_thread* parameter to the
  2042. `(Gui.)run()^` method was set to True, or you are running in an IPython notebook
  2043. context.
  2044. """
  2045. if hasattr(self, "_server") and hasattr(self._server, "_thread") and self._server._is_running:
  2046. self._server.stop_thread()
  2047. _TaipyLogger._get_logger().info("Gui server has been stopped.")