gui.py 112 KB

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