1
0

gui.py 129 KB

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