gui.py 134 KB

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