constants.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """Constants used throughout the package."""
  2. import os
  3. import re
  4. from enum import Enum
  5. from types import SimpleNamespace
  6. import pkg_resources
  7. # App names and versions.
  8. # The name of the Pynecone module.
  9. MODULE_NAME = "pynecone"
  10. # The name of the pip install package.
  11. PACKAGE_NAME = "pynecone"
  12. # The current version of Pynecone.
  13. VERSION = pkg_resources.get_distribution(PACKAGE_NAME).version
  14. # Minimum version of Node.js required to run Pynecone.
  15. MIN_NODE_VERSION = "12.22.0"
  16. # Valid bun versions.
  17. MIN_BUN_VERSION = "0.5.8"
  18. MAX_BUN_VERSION = "0.5.9"
  19. INVALID_BUN_VERSIONS = ["0.5.5", "0.5.6", "0.5.7"]
  20. # Files and directories used to init a new project.
  21. # The root directory of the pynecone library.
  22. ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  23. # The name of the assets directory.
  24. APP_ASSETS_DIR = "assets"
  25. # The template directory used during pc init.
  26. TEMPLATE_DIR = os.path.join(ROOT_DIR, MODULE_NAME, ".templates")
  27. # The web subdirectory of the template directory.
  28. WEB_TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, "web")
  29. # The assets subdirectory of the template directory.
  30. ASSETS_TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, APP_ASSETS_DIR)
  31. # The frontend directories in a project.
  32. # The web folder where the NextJS app is compiled to.
  33. WEB_DIR = ".web"
  34. # The name of the utils file.
  35. UTILS_DIR = "utils"
  36. # The name of the state file.
  37. STATE_PATH = "/".join([UTILS_DIR, "state"])
  38. # The name of the components file.
  39. COMPONENTS_PATH = "/".join([UTILS_DIR, "components"])
  40. # The directory where the app pages are compiled to.
  41. WEB_PAGES_DIR = os.path.join(WEB_DIR, "pages")
  42. # The directory where the static build is located.
  43. WEB_STATIC_DIR = os.path.join(WEB_DIR, "_static")
  44. # The directory where the utils file is located.
  45. WEB_UTILS_DIR = os.path.join(WEB_DIR, UTILS_DIR)
  46. # The directory where the assets are located.
  47. WEB_ASSETS_DIR = os.path.join(WEB_DIR, "public")
  48. # The sitemap config file.
  49. SITEMAP_CONFIG_FILE = os.path.join(WEB_DIR, "next-sitemap.config.js")
  50. # The node modules directory.
  51. NODE_MODULES = "node_modules"
  52. # The package lock file.
  53. PACKAGE_LOCK = "package-lock.json"
  54. # The pcversion app file.
  55. PCVERSION_APP_FILE = os.path.join(WEB_DIR, "pynecone.json")
  56. # Commands to run the app.
  57. # The frontend default port.
  58. FRONTEND_PORT = "3000"
  59. # The backend default port.
  60. BACKEND_PORT = "8000"
  61. # The backend api url.
  62. API_URL = "http://localhost:8000"
  63. # The default path where bun is installed.
  64. BUN_PATH = "$HOME/.bun/bin/bun"
  65. # Command to install bun.
  66. INSTALL_BUN = "curl -fsSL https://bun.sh/install | bash -s -- bun-v0.5.9"
  67. # Default host in dev mode.
  68. BACKEND_HOST = "0.0.0.0"
  69. # The default timeout when launching the gunicorn server.
  70. TIMEOUT = 120
  71. # The command to run the backend in production mode.
  72. RUN_BACKEND_PROD = f"gunicorn --worker-class uvicorn.workers.UvicornH11Worker --preload --timeout {TIMEOUT} --log-level critical".split()
  73. RUN_BACKEND_PROD_WINDOWS = f"uvicorn --timeout-keep-alive {TIMEOUT}".split()
  74. # Socket.IO web server
  75. PING_INTERVAL = 25
  76. PING_TIMEOUT = 120
  77. # Compiler variables.
  78. # The extension for compiled Javascript files.
  79. JS_EXT = ".js"
  80. # The extension for python files.
  81. PY_EXT = ".py"
  82. # The expected variable name where the pc.App is stored.
  83. APP_VAR = "app"
  84. # The expected variable name where the API object is stored for deployment.
  85. API_VAR = "api"
  86. # The name of the router variable.
  87. ROUTER = "router"
  88. # The name of the socket variable.
  89. SOCKET = "socket"
  90. # The name of the variable to hold API results.
  91. RESULT = "result"
  92. # The name of the process variable.
  93. PROCESSING = "processing"
  94. # The name of the state variable.
  95. STATE = "state"
  96. # The name of the events variable.
  97. EVENTS = "events"
  98. # The name of the initial hydrate event.
  99. HYDRATE = "hydrate"
  100. # The name of the index page.
  101. INDEX_ROUTE = "index"
  102. # The name of the document root page.
  103. DOCUMENT_ROOT = "_document"
  104. # The name of the theme page.
  105. THEME = "theme"
  106. # The prefix used to create setters for state vars.
  107. SETTER_PREFIX = "set_"
  108. # The name of the frontend zip during deployment.
  109. FRONTEND_ZIP = "frontend.zip"
  110. # The name of the backend zip during deployment.
  111. BACKEND_ZIP = "backend.zip"
  112. # The name of the sqlite database.
  113. DB_NAME = "pynecone.db"
  114. # The sqlite url.
  115. DB_URL = f"sqlite:///{DB_NAME}"
  116. # The default title to show for Pynecone apps.
  117. DEFAULT_TITLE = "Pynecone App"
  118. # The default description to show for Pynecone apps.
  119. DEFAULT_DESCRIPTION = "A Pynecone app."
  120. # The default image to show for Pynecone apps.
  121. DEFAULT_IMAGE = "favicon.ico"
  122. # The default meta list to show for Pynecone apps.
  123. DEFAULT_META_LIST = []
  124. # The gitignore file.
  125. GITIGNORE_FILE = ".gitignore"
  126. # Files to gitignore.
  127. DEFAULT_GITIGNORE = {WEB_DIR, DB_NAME}
  128. # The name of the pynecone config module.
  129. CONFIG_MODULE = "pcconfig"
  130. # The python config file.
  131. CONFIG_FILE = f"{CONFIG_MODULE}{PY_EXT}"
  132. # The deployment URL.
  133. PRODUCTION_BACKEND_URL = "https://{username}-{app_name}.api.pynecone.app"
  134. # Token expiration time in seconds.
  135. TOKEN_EXPIRATION = 60 * 60
  136. # Env modes
  137. class Env(str, Enum):
  138. """The environment modes."""
  139. DEV = "dev"
  140. PROD = "prod"
  141. # Log levels
  142. class LogLevel(str, Enum):
  143. """The log levels."""
  144. DEBUG = "debug"
  145. INFO = "info"
  146. WARNING = "warning"
  147. ERROR = "error"
  148. CRITICAL = "critical"
  149. # Templates
  150. class Template(str, Enum):
  151. """The templates to use for the app."""
  152. DEFAULT = "default"
  153. COUNTER = "counter"
  154. class Endpoint(Enum):
  155. """Endpoints for the pynecone backend API."""
  156. PING = "ping"
  157. EVENT = "event"
  158. UPLOAD = "upload"
  159. def __str__(self) -> str:
  160. """Get the string representation of the endpoint.
  161. Returns:
  162. The path for the endpoint.
  163. """
  164. return f"/{self.value}"
  165. def get_url(self) -> str:
  166. """Get the URL for the endpoint.
  167. Returns:
  168. The full URL for the endpoint.
  169. """
  170. # Import here to avoid circular imports.
  171. from pynecone.config import get_config
  172. # Get the API URL from the config.
  173. config = get_config()
  174. url = "".join([config.api_url, str(self)])
  175. # The event endpoint is a websocket.
  176. if self == Endpoint.EVENT:
  177. # Replace the protocol with ws.
  178. url = url.replace("https://", "wss://").replace("http://", "ws://")
  179. # Return the url.
  180. return url
  181. class SocketEvent(Enum):
  182. """Socket events sent by the pynecone backend API."""
  183. PING = "ping"
  184. EVENT = "event"
  185. def __str__(self) -> str:
  186. """Get the string representation of the event name.
  187. Returns:
  188. The event name string.
  189. """
  190. return str(self.value)
  191. class Transports(Enum):
  192. """Socket transports used by the pynecone backend API."""
  193. POLLING_WEBSOCKET = "['polling', 'websocket']"
  194. WEBSOCKET_POLLING = "['websocket', 'polling']"
  195. WEBSOCKET_ONLY = "['websocket']"
  196. POLLING_ONLY = "['polling']"
  197. def __str__(self) -> str:
  198. """Get the string representation of the transports.
  199. Returns:
  200. The transports string.
  201. """
  202. return str(self.value)
  203. def get_transports(self) -> str:
  204. """Get the transports config for the backend.
  205. Returns:
  206. The transports config for the backend.
  207. """
  208. # Import here to avoid circular imports.
  209. from pynecone.config import get_config
  210. # Get the API URL from the config.
  211. config = get_config()
  212. return str(config.backend_transports)
  213. class RouteArgType(SimpleNamespace):
  214. """Type of dynamic route arg extracted from URI route."""
  215. # Typecast to str is needed for Enum to work.
  216. SINGLE = str("arg_single")
  217. LIST = str("arg_list")
  218. class RouteVar(SimpleNamespace):
  219. """Names of variables used in the router_data dict stored in State."""
  220. CLIENT_IP = "ip"
  221. CLIENT_TOKEN = "token"
  222. HEADERS = "headers"
  223. PATH = "pathname"
  224. SESSION_ID = "sid"
  225. QUERY = "query"
  226. class RouteRegex(SimpleNamespace):
  227. """Regex used for extracting route args in route."""
  228. ARG = re.compile(r"\[(?!\.)([^\[\]]+)\]")
  229. # group return the catchall pattern (i.e. "[[..slug]]")
  230. CATCHALL = re.compile(r"(\[?\[\.{3}(?![0-9]).*\]?\])")
  231. # group return the arg name (i.e. "slug")
  232. STRICT_CATCHALL = re.compile(r"\[\.{3}([a-zA-Z_][\w]*)\]")
  233. # group return the arg name (i.e. "slug")
  234. OPT_CATCHALL = re.compile(r"\[\[\.{3}([a-zA-Z_][\w]*)\]\]")
  235. # 404 variables
  236. ROOT_404 = ""
  237. SLUG_404 = "[..._]"
  238. TITLE_404 = "404 - Not Found"
  239. FAVICON_404 = "favicon.ico"
  240. DESCRIPTION_404 = "The page was not found"
  241. # Color mode variables
  242. USE_COLOR_MODE = "useColorMode"
  243. COLOR_MODE = "colorMode"
  244. TOGGLE_COLOR_MODE = "toggleColorMode"
  245. # Server socket configuration variables
  246. CORS_ALLOWED_ORIGINS = "*"
  247. POLLING_MAX_HTTP_BUFFER_SIZE = 1000 * 1000