gui.py 139 KB

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