gui.py 110 KB

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