gui.py 108 KB

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