1
0

server.py 14 KB

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