utils.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. """General utility functions."""
  2. from __future__ import annotations
  3. import inspect
  4. import json
  5. import os
  6. import random
  7. import re
  8. import shutil
  9. import signal
  10. import string
  11. import subprocess
  12. import sys
  13. from collections import defaultdict
  14. from subprocess import PIPE
  15. from typing import _GenericAlias # type: ignore
  16. from typing import _UnionGenericAlias # type: ignore
  17. from typing import (
  18. TYPE_CHECKING,
  19. Any,
  20. Callable,
  21. Dict,
  22. List,
  23. Optional,
  24. Tuple,
  25. Type,
  26. Union,
  27. )
  28. import plotly.graph_objects as go
  29. from plotly.io import to_json
  30. from rich.console import Console
  31. from pynecone import constants
  32. if TYPE_CHECKING:
  33. from pynecone.components.component import ImportDict
  34. from pynecone.config import Config
  35. from pynecone.event import Event, EventHandler, EventSpec
  36. from pynecone.var import Var
  37. # Shorthand for join.
  38. join = os.linesep.join
  39. # Console for pretty printing.
  40. console = Console()
  41. def get_args(alias: _GenericAlias) -> Tuple[Type, ...]:
  42. """Get the arguments of a type alias.
  43. Args:
  44. alias: The type alias.
  45. Returns:
  46. The arguments of the type alias.
  47. """
  48. return alias.__args__
  49. def get_base_class(cls: Type) -> Type:
  50. """Get the base class of a class.
  51. Args:
  52. cls: The class.
  53. Returns:
  54. The base class of the class.
  55. """
  56. # For newer versions of Python.
  57. try:
  58. from types import GenericAlias
  59. if isinstance(cls, GenericAlias):
  60. return get_base_class(cls.__origin__)
  61. except:
  62. pass
  63. # Check Union types first.
  64. if isinstance(cls, _UnionGenericAlias):
  65. return tuple(get_base_class(arg) for arg in get_args(cls))
  66. # Check other generic aliases.
  67. if isinstance(cls, _GenericAlias):
  68. return get_base_class(cls.__origin__)
  69. # This is the base class.
  70. return cls
  71. def _issubclass(
  72. cls: Union[Type, _GenericAlias], cls_check: Union[Type, _GenericAlias]
  73. ) -> bool:
  74. """Check if a class is a subclass of another class.
  75. Args:
  76. cls: The class to check.
  77. cls_check: The class to check against.
  78. Returns:
  79. Whether the class is a subclass of the other class.
  80. """
  81. # Special check for Any.
  82. if cls_check == Any:
  83. return True
  84. if cls == Any:
  85. return False
  86. cls_base = get_base_class(cls)
  87. cls_check_base = get_base_class(cls_check)
  88. return cls_check_base == Any or issubclass(cls_base, cls_check_base)
  89. def _isinstance(obj: Any, cls: Union[Type, _GenericAlias]) -> bool:
  90. """Check if an object is an instance of a class.
  91. Args:
  92. obj: The object to check.
  93. cls: The class to check against.
  94. Returns:
  95. Whether the object is an instance of the class.
  96. """
  97. return isinstance(obj, get_base_class(cls))
  98. def rm(path: str):
  99. """Remove a file or directory.
  100. Args:
  101. path: The path to the file or directory.
  102. """
  103. if os.path.isdir(path):
  104. shutil.rmtree(path)
  105. elif os.path.isfile(path):
  106. os.remove(path)
  107. def cp(src: str, dest: str, overwrite: bool = True) -> bool:
  108. """Copy a file or directory.
  109. Args:
  110. src: The path to the file or directory.
  111. dest: The path to the destination.
  112. overwrite: Whether to overwrite the destination.
  113. Returns:
  114. Whether the copy was successful.
  115. """
  116. if src == dest:
  117. return False
  118. if not overwrite and os.path.exists(dest):
  119. return False
  120. if os.path.isdir(src):
  121. rm(dest)
  122. shutil.copytree(src, dest)
  123. else:
  124. shutil.copyfile(src, dest)
  125. return True
  126. def mv(src: str, dest: str, overwrite: bool = True) -> bool:
  127. """Move a file or directory.
  128. Args:
  129. src: The path to the file or directory.
  130. dest: The path to the destination.
  131. overwrite: Whether to overwrite the destination.
  132. Returns:
  133. Whether the move was successful.
  134. """
  135. if src == dest:
  136. return False
  137. if not overwrite and os.path.exists(dest):
  138. return False
  139. rm(dest)
  140. shutil.move(src, dest)
  141. return True
  142. def mkdir(path: str):
  143. """Create a directory.
  144. Args:
  145. path: The path to the directory.
  146. """
  147. if not os.path.exists(path):
  148. os.makedirs(path)
  149. def ln(src: str, dest: str, overwrite: bool = False) -> bool:
  150. """Create a symbolic link.
  151. Args:
  152. src: The path to the file or directory.
  153. dest: The path to the destination.
  154. overwrite: Whether to overwrite the destination.
  155. Returns:
  156. Whether the link was successful.
  157. """
  158. if src == dest:
  159. return False
  160. if not overwrite and (os.path.exists(dest) or os.path.islink(dest)):
  161. return False
  162. if os.path.isdir(src):
  163. rm(dest)
  164. os.symlink(src, dest, target_is_directory=True)
  165. else:
  166. os.symlink(src, dest)
  167. return True
  168. def kill(pid):
  169. """Kill a process.
  170. Args:
  171. pid: The process ID.
  172. """
  173. os.kill(pid, signal.SIGTERM)
  174. def which(program: str) -> Optional[str]:
  175. """Find the path to an executable.
  176. Args:
  177. program: The name of the executable.
  178. Returns:
  179. The path to the executable.
  180. """
  181. return shutil.which(program)
  182. def get_config() -> Config:
  183. """Get the app config.
  184. Returns:
  185. The app config.
  186. """
  187. sys.path.append(os.getcwd())
  188. return __import__(constants.CONFIG_MODULE).config
  189. def get_bun_path():
  190. """Get the path to the bun executable.
  191. Returns:
  192. The path to the bun executable.
  193. """
  194. return os.path.expandvars(get_config().bun_path)
  195. def get_app() -> Any:
  196. """Get the app based on the default config.
  197. Returns:
  198. The app based on the default config.
  199. """
  200. config = get_config()
  201. module = ".".join([config.app_name, config.app_name])
  202. app = __import__(module, fromlist=(constants.APP_VAR,))
  203. return app
  204. def install_dependencies():
  205. """Install the dependencies."""
  206. subprocess.call([get_bun_path(), "install"], cwd=constants.WEB_DIR, stdout=PIPE)
  207. def export_app(app):
  208. """Zip up the app for deployment.
  209. Args:
  210. app: The app.
  211. """
  212. app.app.compile(ignore_env=False)
  213. cmd = r"rm -rf .web/_static; cd .web && bun run export && cd _static && zip -r ../../frontend.zip ./* && cd ../.. && zip -r backend.zip ./* -x .web/\* ./assets\* ./frontend.zip\* ./backend.zip\*"
  214. os.system(cmd)
  215. def setup_frontend(app):
  216. """Set up the frontend.
  217. Args:
  218. app: The app.
  219. """
  220. # Initialize the web directory if it doesn't exist.
  221. cp(constants.WEB_TEMPLATE_DIR, constants.WEB_DIR, overwrite=False)
  222. # Install the frontend dependencies.
  223. console.rule("[bold]Installing Dependencies")
  224. install_dependencies()
  225. # Link the assets folder.
  226. ln(src=os.path.join("..", constants.APP_ASSETS_DIR), dest=constants.WEB_ASSETS_DIR)
  227. # Compile the frontend.
  228. app.app.compile(ignore_env=False)
  229. def run_frontend(app) -> subprocess.Popen:
  230. """Run the frontend.
  231. Args:
  232. app: The app.
  233. Returns:
  234. The frontend process.
  235. """
  236. setup_frontend(app)
  237. command = [get_bun_path(), "run", "dev"]
  238. console.rule("[bold green]App Running")
  239. return subprocess.Popen(
  240. command, cwd=constants.WEB_DIR
  241. ) # stdout=PIPE to hide output
  242. def run_frontend_prod(app) -> subprocess.Popen:
  243. """Run the frontend.
  244. Args:
  245. app: The app.
  246. Returns:
  247. The frontend process.
  248. """
  249. setup_frontend(app)
  250. # Export and zip up the frontend and backend then start the frontend in production mode.
  251. cmd = r"rm -rf .web/_static || true; cd .web && bun run export"
  252. os.system(cmd)
  253. command = [get_bun_path(), "run", "prod"]
  254. return subprocess.Popen(command, cwd=constants.WEB_DIR)
  255. def run_backend(app):
  256. """Run the backend.
  257. Args:
  258. app: The app.
  259. """
  260. command = constants.RUN_BACKEND + [
  261. f"{app.__name__}:{constants.APP_VAR}.{constants.API_VAR}"
  262. ]
  263. subprocess.call(command)
  264. def run_backend_prod(app) -> None:
  265. """Run the backend.
  266. Args:
  267. app: The app.
  268. """
  269. command = constants.RUN_BACKEND_PROD + [f"{app.__name__}:{constants.API_VAR}"]
  270. subprocess.call(command)
  271. def get_production_backend_url() -> str:
  272. """Get the production backend URL.
  273. Returns:
  274. The production backend URL.
  275. """
  276. config = get_config()
  277. return constants.PRODUCTION_BACKEND_URL.format(
  278. username=config.username,
  279. app_name=config.app_name,
  280. )
  281. def to_snake_case(text: str) -> str:
  282. """Convert a string to snake case.
  283. The words in the text are converted to lowercase and
  284. separated by underscores.
  285. Args:
  286. text: The string to convert.
  287. Returns:
  288. The snake case string.
  289. """
  290. s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", text)
  291. return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
  292. def to_camel_case(text: str) -> str:
  293. """Convert a string to camel case.
  294. The first word in the text is converted to lowercase and
  295. the rest of the words are converted to title case, removing underscores.
  296. Args:
  297. text: The string to convert.
  298. Returns:
  299. The camel case string.
  300. """
  301. if "_" not in text:
  302. return text
  303. camel = "".join(
  304. word.capitalize() if i > 0 else word.lower()
  305. for i, word in enumerate(text.lstrip("_").split("_"))
  306. )
  307. prefix = "_" if text.startswith("_") else ""
  308. return prefix + camel
  309. def to_title(text: str) -> str:
  310. """Convert a string from snake case to a title.
  311. Each word is converted to title case and separated by a space.
  312. Args:
  313. text: The string to convert.
  314. Returns:
  315. The title case string.
  316. """
  317. return " ".join(word.capitalize() for word in text.split("_"))
  318. WRAP_MAP = {
  319. "{": "}",
  320. "(": ")",
  321. "[": "]",
  322. "<": ">",
  323. '"': '"',
  324. "'": "'",
  325. "`": "`",
  326. }
  327. def get_close_char(open: str, close: Optional[str] = None) -> str:
  328. """Check if the given character is a valid brace.
  329. Args:
  330. open: The open character.
  331. close: The close character if provided.
  332. Returns:
  333. The close character.
  334. Raises:
  335. ValueError: If the open character is not a valid brace.
  336. """
  337. if close is not None:
  338. return close
  339. if open not in WRAP_MAP:
  340. raise ValueError(f"Invalid wrap open: {open}, must be one of {WRAP_MAP.keys()}")
  341. return WRAP_MAP[open]
  342. def is_wrapped(text: str, open: str, close: Optional[str] = None) -> bool:
  343. """Check if the given text is wrapped in the given open and close characters.
  344. Args:
  345. text: The text to check.
  346. open: The open character.
  347. close: The close character.
  348. Returns:
  349. Whether the text is wrapped.
  350. """
  351. close = get_close_char(open, close)
  352. return text.startswith(open) and text.endswith(close)
  353. def wrap(
  354. text: str,
  355. open: str,
  356. close: Optional[str] = None,
  357. check_first: bool = True,
  358. num: int = 1,
  359. ) -> str:
  360. """Wrap the given text in the given open and close characters.
  361. Args:
  362. text: The text to wrap.
  363. open: The open character.
  364. close: The close character.
  365. check_first: Whether to check if the text is already wrapped.
  366. num: The number of times to wrap the text.
  367. Returns:
  368. The wrapped text.
  369. """
  370. close = get_close_char(open, close)
  371. # If desired, check if the text is already wrapped in braces.
  372. if check_first and is_wrapped(text=text, open=open, close=close):
  373. return text
  374. # Wrap the text in braces.
  375. return f"{open * num}{text}{close * num}"
  376. def indent(text: str, indent_level: int = 2) -> str:
  377. """Indent the given text by the given indent level.
  378. Args:
  379. text: The text to indent.
  380. indent_level: The indent level.
  381. Returns:
  382. The indented text.
  383. """
  384. lines = text.splitlines()
  385. if len(lines) < 2:
  386. return text
  387. return os.linesep.join(f"{' ' * indent_level}{line}" for line in lines) + os.linesep
  388. def get_page_path(path: str) -> str:
  389. """Get the path of the compiled JS file for the given page.
  390. Args:
  391. path: The path of the page.
  392. Returns:
  393. The path of the compiled JS file.
  394. """
  395. return os.path.join(constants.WEB_PAGES_DIR, path + constants.JS_EXT)
  396. def get_theme_path() -> str:
  397. """Get the path of the base theme style.
  398. Returns:
  399. The path of the theme style.
  400. """
  401. return os.path.join(constants.WEB_UTILS_DIR, constants.THEME + constants.JS_EXT)
  402. def write_page(path: str, code: str):
  403. """Write the given code to the given path.
  404. Args:
  405. path: The path to write the code to.
  406. code: The code to write.
  407. """
  408. mkdir(os.path.dirname(path))
  409. with open(path, "w") as f:
  410. f.write(code)
  411. def format_route(route: str):
  412. """Format the given route.
  413. Args:
  414. route: The route to format.
  415. Returns:
  416. The formatted route.
  417. """
  418. route = route.strip(os.path.sep)
  419. route = to_snake_case(route).replace("_", "-")
  420. if route == "":
  421. return constants.INDEX_ROUTE
  422. return route
  423. def format_cond(
  424. cond: str, true_value: str, false_value: str = '""', is_nested: bool = False
  425. ) -> str:
  426. """Format a conditional expression.
  427. Args:
  428. cond: The cond.
  429. true_value: The value to return if the cond is true.
  430. false_value: The value to return if the cond is false.
  431. is_nested: Whether the cond is nested.
  432. Returns:
  433. The formatted conditional expression.
  434. """
  435. expr = f"{cond} ? {true_value} : {false_value}"
  436. if not is_nested:
  437. expr = wrap(expr, "{")
  438. return expr
  439. def format_event_fn(fn: Callable) -> str:
  440. """Format a function as an event.
  441. Args:
  442. fn: The function to format.
  443. Returns:
  444. The formatted function.
  445. """
  446. from pynecone.event import EventHandler
  447. if isinstance(fn, EventHandler):
  448. fn = fn.fn
  449. return to_snake_case(fn.__qualname__)
  450. def format_event(event_spec: EventSpec) -> str:
  451. """Format an event.
  452. Args:
  453. event_spec: The event to format.
  454. Returns:
  455. The compiled event.
  456. """
  457. args = ",".join([":".join((name, val)) for name, val in event_spec.args])
  458. return f"E(\"{format_event_fn(event_spec.handler.fn)}\", {wrap(args, '{')})"
  459. USED_VARIABLES = set()
  460. def get_unique_variable_name() -> str:
  461. """Get a unique variable name.
  462. Returns:
  463. The unique variable name.
  464. """
  465. name = "".join([random.choice(string.ascii_lowercase) for _ in range(8)])
  466. if name not in USED_VARIABLES:
  467. USED_VARIABLES.add(name)
  468. return name
  469. return get_unique_variable_name()
  470. def get_default_app_name() -> str:
  471. """Get the default app name.
  472. The default app name is the name of the current directory.
  473. Returns:
  474. The default app name.
  475. """
  476. return os.getcwd().split(os.path.sep)[-1].replace("-", "_")
  477. def is_dataframe(value: Type) -> bool:
  478. """Check if the given value is a dataframe.
  479. Args:
  480. value: The value to check.
  481. Returns:
  482. Whether the value is a dataframe.
  483. """
  484. return value.__name__ == "DataFrame"
  485. def format_state(value: Any) -> Dict:
  486. """Recursively format values in the given state.
  487. Args:
  488. value: The state to format.
  489. Returns:
  490. The formatted state.
  491. """
  492. if isinstance(value, go.Figure):
  493. return json.loads(to_json(value))["data"]
  494. if is_dataframe(type(value)):
  495. return {
  496. "columns": value.columns.tolist(),
  497. "data": value.values.tolist(),
  498. }
  499. if isinstance(value, dict):
  500. return {k: format_state(v) for k, v in value.items()}
  501. return value
  502. def get_event(state, event):
  503. """Get the event from the given state.
  504. Args:
  505. state: The state.
  506. event: The event.
  507. Returns:
  508. The event.
  509. """
  510. return f"{state.get_name()}.{event}"
  511. def format_string(string: str) -> str:
  512. """Format the given string as a JS string literal..
  513. Args:
  514. string: The string to format.
  515. Returns:
  516. The formatted string.
  517. """
  518. # Escale backticks.
  519. string = string.replace("\`", "`") # type: ignore
  520. string = string.replace("`", "\`") # type: ignore
  521. # Wrap the string so it looks like {`string`}.
  522. string = wrap(string, "`")
  523. string = wrap(string, "{")
  524. return string
  525. def call_event_handler(event_handler: EventHandler, arg: Var) -> EventSpec:
  526. """Call an event handler to get the event spec.
  527. This function will inspect the function signature of the event handler.
  528. If it takes in an arg, the arg will be passed to the event handler.
  529. Otherwise, the event handler will be called with no args.
  530. Args:
  531. event_handler: The event handler.
  532. arg: The argument to pass to the event handler.
  533. Returns:
  534. The event spec from calling the event handler.
  535. """
  536. args = inspect.getfullargspec(event_handler.fn).args
  537. if len(args) == 1:
  538. return event_handler()
  539. assert (
  540. len(args) == 2
  541. ), f"Event handler {event_handler.fn} must have 1 or 2 arguments."
  542. return event_handler(arg)
  543. def call_event_fn(fn: Callable, arg: Var) -> List[EventSpec]:
  544. """Call a function to a list of event specs.
  545. The function should return either a single EventSpec or a list of EventSpecs.
  546. If the function takes in an arg, the arg will be passed to the function.
  547. Otherwise, the function will be called with no args.
  548. Args:
  549. fn: The function to call.
  550. arg: The argument to pass to the function.
  551. Returns:
  552. The event specs from calling the function.
  553. Raises:
  554. ValueError: If the lambda has an invalid signature.
  555. """
  556. args = inspect.getfullargspec(fn).args
  557. if len(args) == 0:
  558. out = fn()
  559. elif len(args) == 1:
  560. out = fn(arg)
  561. else:
  562. raise ValueError(f"Lambda {fn} must have 0 or 1 arguments.")
  563. if not isinstance(out, List):
  564. out = [out]
  565. return out
  566. def get_handler_args(event_spec: EventSpec, arg: Var) -> Tuple[Tuple[str, str], ...]:
  567. """Get the handler args for the given event spec.
  568. Args:
  569. event_spec: The event spec.
  570. arg: The controlled event argument.
  571. Returns:
  572. The handler args.
  573. """
  574. args = inspect.getfullargspec(event_spec.handler.fn).args
  575. if len(args) > 2:
  576. return event_spec.args
  577. else:
  578. return ((args[1], arg.name),)
  579. def fix_events(events: Optional[List[Event]], token: str) -> List[Event]:
  580. """Fix a list of events returned by an event handler.
  581. Args:
  582. events: The events to fix.
  583. token: The user token.
  584. Returns:
  585. The fixed events.
  586. """
  587. from pynecone.event import Event, EventHandler, EventSpec
  588. # If the event handler returns nothing, return an empty list.
  589. if events is None:
  590. return []
  591. # If the handler returns a single event, wrap it in a list.
  592. if not isinstance(events, List):
  593. events = [events]
  594. # Fix the events created by the handler.
  595. out = []
  596. for e in events:
  597. # If it is already an event, don't modify it.
  598. if isinstance(e, Event):
  599. name = e.name
  600. payload = e.payload
  601. # Otherwise, create an event from the event spec.
  602. else:
  603. if isinstance(e, EventHandler):
  604. e = e()
  605. assert isinstance(e, EventSpec), f"Unexpected event type, {type(e)}."
  606. name = format_event_fn(e.handler.fn)
  607. payload = dict(e.args)
  608. # Create an event and append it to the list.
  609. out.append(
  610. Event(
  611. token=token,
  612. name=name,
  613. payload=payload,
  614. )
  615. )
  616. return out
  617. def merge_imports(*imports) -> ImportDict:
  618. """Merge two import dicts together.
  619. Args:
  620. *imports: The list of import dicts to merge.
  621. Returns:
  622. The merged import dicts.
  623. """
  624. all_imports = defaultdict(set)
  625. for import_dict in imports:
  626. for lib, fields in import_dict.items():
  627. for field in fields:
  628. all_imports[lib].add(field)
  629. return all_imports
  630. def get_hydrate_event(state) -> str:
  631. """Get the name of the hydrate event for the state.
  632. Args:
  633. state: The state.
  634. Returns:
  635. The name of the hydrate event.
  636. """
  637. return get_event(state, constants.HYDRATE)
  638. def get_redis():
  639. """Get the redis client.
  640. Returns:
  641. The redis client.
  642. """
  643. try:
  644. import redis
  645. except:
  646. return None
  647. config = get_config()
  648. if config.redis_url is None:
  649. return None
  650. redis_url, redis_port = config.redis_url.split(":")
  651. print("Using redis at", config.redis_url)
  652. return redis.Redis(host=redis_url, port=int(redis_port), db=0)