gui.py 135 KB

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