gui.py 107 KB

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