gui.py 123 KB

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