1
0

gui.py 135 KB

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