utils.py 24 KB

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