server.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 logging
  14. import os
  15. import pathlib
  16. import re
  17. import sys
  18. import time
  19. import typing as t
  20. import webbrowser
  21. from importlib import util
  22. from random import randint
  23. from flask import Blueprint, Flask, json, jsonify, render_template, request, send_from_directory
  24. from flask_cors import CORS
  25. from flask_socketio import SocketIO
  26. from gitignore_parser import parse_gitignore
  27. from kthread import KThread
  28. from werkzeug.serving import is_running_from_reloader
  29. import __main__
  30. from taipy.logger._taipy_logger import _TaipyLogger
  31. from ._renderers.json import _TaipyJsonProvider
  32. from .config import ServerConfig
  33. from .custom._page import _ExternalResourceHandlerManager
  34. from .utils import _is_in_notebook, _is_port_open, _RuntimeManager
  35. if t.TYPE_CHECKING:
  36. from .gui import Gui
  37. class _Server:
  38. __RE_OPENING_CURLY = re.compile(r"([^\"])(\{)")
  39. __RE_CLOSING_CURLY = re.compile(r"(\})([^\"])")
  40. __OPENING_CURLY = r"\1{"
  41. __CLOSING_CURLY = r"}\2"
  42. _RESOURCE_HANDLER_ARG = "tprh"
  43. def __init__(
  44. self,
  45. gui: Gui,
  46. flask: t.Optional[Flask] = None,
  47. path_mapping: t.Optional[dict] = None,
  48. async_mode: t.Optional[str] = None,
  49. allow_upgrades: bool = True,
  50. server_config: t.Optional[ServerConfig] = None,
  51. ):
  52. self._gui = gui
  53. server_config = server_config or {}
  54. self._flask = flask
  55. if self._flask is None:
  56. flask_config: t.Dict[str, t.Any] = {"import_name": "Taipy"}
  57. if "flask" in server_config and isinstance(server_config["flask"], dict):
  58. flask_config.update(server_config["flask"])
  59. self._flask = Flask(**flask_config)
  60. if "SECRET_KEY" not in self._flask.config or not self._flask.config["SECRET_KEY"]:
  61. self._flask.config["SECRET_KEY"] = "TaIpY"
  62. # setup cors
  63. if "cors" not in server_config or (
  64. "cors" in server_config and (isinstance(server_config["cors"], dict) or server_config["cors"] is True)
  65. ):
  66. cors_config = (
  67. server_config["cors"] if "cors" in server_config and isinstance(server_config["cors"], dict) else {}
  68. )
  69. CORS(self._flask, **cors_config)
  70. # setup socketio
  71. socketio_config: t.Dict[str, t.Any] = {
  72. "cors_allowed_origins": "*",
  73. "ping_timeout": 10,
  74. "ping_interval": 5,
  75. "json": json,
  76. "async_mode": async_mode,
  77. "allow_upgrades": allow_upgrades,
  78. }
  79. if "socketio" in server_config and isinstance(server_config["socketio"], dict):
  80. socketio_config.update(server_config["socketio"])
  81. self._ws = SocketIO(self._flask, **socketio_config)
  82. self._apply_patch()
  83. # set json encoder (for Taipy specific types)
  84. self._flask.json_provider_class = _TaipyJsonProvider
  85. self._flask.json = self._flask.json_provider_class(self._flask) # type: ignore
  86. self.__path_mapping = path_mapping or {}
  87. self.__ssl_context = server_config.get("ssl_context", None)
  88. self._is_running = False
  89. # Websocket (handle json message)
  90. # adding args for the one call with a server ack request
  91. @self._ws.on("message")
  92. def handle_message(message, *args) -> None:
  93. if "status" in message:
  94. _TaipyLogger._get_logger().info(message["status"])
  95. elif "type" in message:
  96. gui._manage_message(message["type"], message)
  97. @self._ws.on("connect")
  98. def handle_connect():
  99. gui._handle_connect()
  100. @self._ws.on("disconnect")
  101. def handle_disconnect():
  102. gui._handle_disconnect()
  103. def __is_ignored(self, file_path: str) -> bool:
  104. if not hasattr(self, "_ignore_matches"):
  105. __IGNORE_FILE = ".taipyignore"
  106. ignore_file = (
  107. (pathlib.Path(__main__.__file__).parent / __IGNORE_FILE) if hasattr(__main__, "__file__") else None
  108. )
  109. if not ignore_file or not ignore_file.is_file():
  110. ignore_file = pathlib.Path(self._gui._root_dir) / __IGNORE_FILE
  111. self._ignore_matches = (
  112. parse_gitignore(ignore_file) if ignore_file.is_file() and os.access(ignore_file, os.R_OK) else None
  113. )
  114. if callable(self._ignore_matches):
  115. return self._ignore_matches(file_path)
  116. return False
  117. def _get_default_blueprint(
  118. self,
  119. static_folder: str,
  120. template_folder: str,
  121. title: str,
  122. favicon: str,
  123. root_margin: str,
  124. scripts: t.List[str],
  125. styles: t.List[str],
  126. version: str,
  127. client_config: t.Dict[str, t.Any],
  128. watermark: t.Optional[str],
  129. css_vars: str,
  130. base_url: str,
  131. ) -> Blueprint:
  132. taipy_bp = Blueprint("Taipy", __name__, static_folder=static_folder, template_folder=template_folder)
  133. # Serve static react build
  134. @taipy_bp.route("/", defaults={"path": ""})
  135. @taipy_bp.route("/<path:path>")
  136. def my_index(path):
  137. resource_handler_id = request.cookies.get(_Server._RESOURCE_HANDLER_ARG, None)
  138. if resource_handler_id is not None:
  139. resource_handler = _ExternalResourceHandlerManager().get(resource_handler_id)
  140. if resource_handler is None:
  141. return (f"Invalid value for query {_Server._RESOURCE_HANDLER_ARG}", 404)
  142. try:
  143. return resource_handler.get_resources(path, static_folder)
  144. except Exception as e:
  145. raise RuntimeError("Can't get resources from custom resource handler") from e
  146. if path == "" or path == "index.html" or "." not in path:
  147. try:
  148. return render_template(
  149. "index.html",
  150. title=title,
  151. favicon=favicon,
  152. root_margin=root_margin,
  153. watermark=watermark,
  154. config=client_config,
  155. scripts=scripts,
  156. styles=styles,
  157. version=version,
  158. css_vars=css_vars,
  159. base_url=base_url,
  160. )
  161. except Exception:
  162. raise RuntimeError(
  163. "Something is wrong with the taipy-gui front-end installation. Check that the js bundle has been properly built (is Node.js installed?)." # noqa: E501
  164. ) from None
  165. if path == "taipy.status.json":
  166. return self._direct_render_json(self._gui._serve_status(pathlib.Path(template_folder) / path))
  167. if str(os.path.normpath(file_path := ((base_path := static_folder + os.path.sep) + path))).startswith(
  168. base_path
  169. ) and os.path.isfile(file_path):
  170. return send_from_directory(base_path, path)
  171. # use the path mapping to detect and find resources
  172. for k, v in self.__path_mapping.items():
  173. if (
  174. path.startswith(f"{k}/")
  175. and str(
  176. os.path.normpath(file_path := ((base_path := v + os.path.sep) + path[len(k) + 1 :]))
  177. ).startswith(base_path)
  178. and os.path.isfile(file_path)
  179. ):
  180. return send_from_directory(base_path, path[len(k) + 1 :])
  181. if (
  182. hasattr(__main__, "__file__")
  183. and str(
  184. os.path.normpath(
  185. file_path := ((base_path := os.path.dirname(__main__.__file__) + os.path.sep) + path)
  186. )
  187. ).startswith(base_path)
  188. and os.path.isfile(file_path)
  189. and not self.__is_ignored(file_path)
  190. ):
  191. return send_from_directory(base_path, path)
  192. if (
  193. str(os.path.normpath(file_path := (base_path := self._gui._root_dir + os.path.sep) + path)).startswith(
  194. base_path
  195. )
  196. and os.path.isfile(file_path)
  197. and not self.__is_ignored(file_path)
  198. ):
  199. return send_from_directory(base_path, path)
  200. return ("", 404)
  201. return taipy_bp
  202. # Update to render as JSX
  203. def _render(self, html_fragment, style, head, context):
  204. template_str = _Server.__RE_OPENING_CURLY.sub(_Server.__OPENING_CURLY, html_fragment)
  205. template_str = _Server.__RE_CLOSING_CURLY.sub(_Server.__CLOSING_CURLY, template_str)
  206. template_str = template_str.replace('"{!', "{")
  207. template_str = template_str.replace('!}"', "}")
  208. return self._direct_render_json(
  209. {
  210. "jsx": template_str,
  211. "style": (style + os.linesep) if style else "",
  212. "head": head or [],
  213. "context": context or self._gui._get_default_module_name(),
  214. }
  215. )
  216. def _direct_render_json(self, data):
  217. return jsonify(data)
  218. def get_flask(self):
  219. return self._flask
  220. def test_client(self):
  221. return self._flask.test_client()
  222. def _run_notebook(self):
  223. self._is_running = True
  224. self._ws.run(self._flask, host=self._host, port=self._port, debug=False, use_reloader=False)
  225. def _get_async_mode(self) -> str:
  226. return self._ws.async_mode
  227. def _apply_patch(self):
  228. if self._get_async_mode() == "gevent" and util.find_spec("gevent"):
  229. from gevent import monkey
  230. if not monkey.is_module_patched("time"):
  231. monkey.patch_time()
  232. if self._get_async_mode() == "eventlet" and util.find_spec("eventlet"):
  233. from eventlet import monkey_patch, patcher
  234. if not patcher.is_monkey_patched("time"):
  235. monkey_patch(time=True)
  236. def _get_random_port(self): # pragma: no cover
  237. while True:
  238. port = randint(49152, 65535)
  239. if port not in _RuntimeManager().get_used_port() and not _is_port_open(self._host, port):
  240. return port
  241. def run(self, host, port, debug, use_reloader, flask_log, run_in_thread, allow_unsafe_werkzeug, notebook_proxy):
  242. host_value = host if host != "0.0.0.0" else "localhost"
  243. self._host = host
  244. if port == "auto":
  245. port = self._get_random_port()
  246. self._port = port
  247. if _is_in_notebook() and notebook_proxy: # pragma: no cover
  248. from .utils.proxy import NotebookProxy
  249. # Start proxy if not already started
  250. self._proxy = NotebookProxy(gui=self._gui, listening_port=port)
  251. self._proxy.run()
  252. self._port = self._get_random_port()
  253. if _is_in_notebook() or run_in_thread:
  254. runtime_manager = _RuntimeManager()
  255. runtime_manager.add_gui(self._gui, port)
  256. if debug and not is_running_from_reloader() and _is_port_open(host_value, port):
  257. raise ConnectionError(
  258. "Port {port} is already opened on {host} because another application is running on the same port. Please pick another port number and rerun with the 'port=<new_port>' option. You can also let Taipy choose a port number for you by running with the 'port=\"auto\"' option." # noqa: E501
  259. )
  260. if not flask_log:
  261. log = logging.getLogger("werkzeug")
  262. log.disabled = True
  263. if not is_running_from_reloader():
  264. _TaipyLogger._get_logger().info(f" * Server starting on http://{host_value}:{port}")
  265. else:
  266. _TaipyLogger._get_logger().info(f" * Server reloaded on http://{host_value}:{port}")
  267. if not is_running_from_reloader() and self._gui._get_config("run_browser", False):
  268. webbrowser.open(f"http://{host_value}{f':{port}' if port else ''}", new=2)
  269. if _is_in_notebook() or run_in_thread:
  270. self._thread = KThread(target=self._run_notebook)
  271. self._thread.start()
  272. return
  273. self._is_running = True
  274. run_config = {
  275. "app": self._flask,
  276. "host": host,
  277. "port": port,
  278. "debug": debug,
  279. "use_reloader": use_reloader,
  280. }
  281. if self.__ssl_context is not None:
  282. run_config["ssl_context"] = self.__ssl_context
  283. # flask-socketio specific conditions for 'allow_unsafe_werkzeug' parameters to be popped out of kwargs
  284. if self._get_async_mode() == "threading" and (not sys.stdin or not sys.stdin.isatty()):
  285. run_config = {**run_config, "allow_unsafe_werkzeug": allow_unsafe_werkzeug}
  286. self._ws.run(**run_config)
  287. def stop_thread(self):
  288. if hasattr(self, "_thread") and self._thread.is_alive() and self._is_running:
  289. self._is_running = False
  290. with contextlib.suppress(Exception):
  291. if self._get_async_mode() == "gevent":
  292. if self._ws.wsgi_server is not None:
  293. self._ws.wsgi_server.stop()
  294. else:
  295. self._thread.kill()
  296. else:
  297. self._thread.kill()
  298. while _is_port_open(self._host, self._port):
  299. time.sleep(0.1)
  300. def stop_proxy(self):
  301. if hasattr(self, "_proxy"):
  302. self._proxy.stop()