constants.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. # Files and directories used to init a new project.
  17. # The root directory of the pynecone library.
  18. ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  19. # The name of the file used for pc init.
  20. APP_TEMPLATE_FILE = "tutorial.py"
  21. # The name of the assets directory.
  22. APP_ASSETS_DIR = "assets"
  23. # The template directory used during pc init.
  24. TEMPLATE_DIR = os.path.join(ROOT_DIR, MODULE_NAME, ".templates")
  25. # The web subdirectory of the template directory.
  26. WEB_TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, "web")
  27. # The app subdirectory of the template directory.
  28. APP_TEMPLATE_DIR = os.path.join(TEMPLATE_DIR, "app")
  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 template file.
  55. PCVERSION_TEMPLATE_FILE = os.path.join(WEB_TEMPLATE_DIR, "pynecone.json")
  56. # The pcversion app file.
  57. PCVERSION_APP_FILE = os.path.join(WEB_DIR, "pynecone.json")
  58. # Commands to run the app.
  59. # The frontend default port.
  60. FRONTEND_PORT = "3000"
  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.5"
  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. # Compiler variables.
  75. # The extension for compiled Javascript files.
  76. JS_EXT = ".js"
  77. # The extension for python files.
  78. PY_EXT = ".py"
  79. # The expected variable name where the pc.App is stored.
  80. APP_VAR = "app"
  81. # The expected variable name where the API object is stored for deployment.
  82. API_VAR = "api"
  83. # The name of the router variable.
  84. ROUTER = "router"
  85. # The name of the socket variable.
  86. SOCKET = "socket"
  87. # The name of the variable to hold API results.
  88. RESULT = "result"
  89. # The name of the process variable.
  90. PROCESSING = "processing"
  91. # The name of the state variable.
  92. STATE = "state"
  93. # The name of the events variable.
  94. EVENTS = "events"
  95. # The name of the initial hydrate event.
  96. HYDRATE = "hydrate"
  97. # The name of the index page.
  98. INDEX_ROUTE = "index"
  99. # The name of the document root page.
  100. DOCUMENT_ROOT = "_document"
  101. # The name of the theme page.
  102. THEME = "theme"
  103. # The prefix used to create setters for state vars.
  104. SETTER_PREFIX = "set_"
  105. # The name of the frontend zip during deployment.
  106. FRONTEND_ZIP = "frontend.zip"
  107. # The name of the backend zip during deployment.
  108. BACKEND_ZIP = "backend.zip"
  109. # The name of the sqlite database.
  110. DB_NAME = "pynecone.db"
  111. # The sqlite url.
  112. DB_URL = f"sqlite:///{DB_NAME}"
  113. # The default title to show for Pynecone apps.
  114. DEFAULT_TITLE = "Pynecone App"
  115. # The default description to show for Pynecone apps.
  116. DEFAULT_DESCRIPTION = "A Pynecone app."
  117. # The default image to show for Pynecone apps.
  118. DEFAULT_IMAGE = "favicon.ico"
  119. # The default meta list to show for Pynecone apps.
  120. DEFAULT_META_LIST = []
  121. # The gitignore file.
  122. GITIGNORE_FILE = ".gitignore"
  123. # Files to gitignore.
  124. DEFAULT_GITIGNORE = {WEB_DIR, DB_NAME}
  125. # The name of the pynecone config module.
  126. CONFIG_MODULE = "pcconfig"
  127. # The python config file.
  128. CONFIG_FILE = f"{CONFIG_MODULE}{PY_EXT}"
  129. # The deployment URL.
  130. PRODUCTION_BACKEND_URL = "https://{username}-{app_name}.api.pynecone.app"
  131. # Token expiration time in seconds.
  132. TOKEN_EXPIRATION = 60 * 60
  133. # Env modes
  134. class Env(str, Enum):
  135. """The environment modes."""
  136. DEV = "dev"
  137. PROD = "prod"
  138. # Log levels
  139. class LogLevel(str, Enum):
  140. """The log levels."""
  141. DEBUG = "debug"
  142. INFO = "info"
  143. WARNING = "warning"
  144. ERROR = "error"
  145. CRITICAL = "critical"
  146. class Endpoint(Enum):
  147. """Endpoints for the pynecone backend API."""
  148. PING = "ping"
  149. EVENT = "event"
  150. def __str__(self) -> str:
  151. """Get the string representation of the endpoint.
  152. Returns:
  153. The path for the endpoint.
  154. """
  155. return f"/{self.value}"
  156. def get_url(self) -> str:
  157. """Get the URL for the endpoint.
  158. Returns:
  159. The full URL for the endpoint.
  160. """
  161. # Import here to avoid circular imports.
  162. from pynecone import utils
  163. # Get the API URL from the config.
  164. config = utils.get_config()
  165. url = "".join([config.api_url, str(self)])
  166. # The event endpoint is a websocket.
  167. if self == Endpoint.EVENT:
  168. # Replace the protocol with ws.
  169. url = url.replace("https://", "wss://").replace("http://", "ws://")
  170. # Return the url.
  171. return url
  172. class SocketEvent(Enum):
  173. """Socket events sent by the pynecone backend API."""
  174. PING = "ping"
  175. EVENT = "event"
  176. def __str__(self) -> str:
  177. """Get the string representation of the event name.
  178. Returns:
  179. The event name string.
  180. """
  181. return str(self.value)
  182. class Transports(Enum):
  183. """Socket transports used by the pynecone backend API."""
  184. POLLING_WEBSOCKET = "['polling', 'websocket']"
  185. WEBSOCKET_POLLING = "['websocket', 'polling']"
  186. WEBSOCKET_ONLY = "['websocket']"
  187. POLLING_ONLY = "['polling']"
  188. def __str__(self) -> str:
  189. """Get the string representation of the transports.
  190. Returns:
  191. The transports string.
  192. """
  193. return str(self.value)
  194. def get_transports(self) -> str:
  195. """Get the transports config for the backend.
  196. Returns:
  197. The transports config for the backend.
  198. """
  199. # Import here to avoid circular imports.
  200. from pynecone import utils
  201. # Get the transports from the config.
  202. config = utils.get_config()
  203. return str(config.backend_transports)
  204. class RouteArgType(SimpleNamespace):
  205. """Type of dynamic route arg extracted from URI route."""
  206. # Typecast to str is needed for Enum to work.
  207. SINGLE = str("arg_single")
  208. LIST = str("arg_list")
  209. class RouteVar(SimpleNamespace):
  210. """Names of variables used in the router_data dict stored in State."""
  211. CLIENT_IP = "ip"
  212. CLIENT_TOKEN = "token"
  213. HEADERS = "headers"
  214. PATH = "pathname"
  215. SESSION_ID = "sid"
  216. QUERY = "query"
  217. class RouteRegex(SimpleNamespace):
  218. """Regex used for extracting route args in route."""
  219. ARG = re.compile(r"\[(?!\.)([^\[\]]+)\]")
  220. # group return the catchall pattern (i.e. "[[..slug]]")
  221. CATCHALL = re.compile(r"(\[?\[\.{3}(?![0-9]).*\]?\])")
  222. # group return the arg name (i.e. "slug")
  223. STRICT_CATCHALL = re.compile(r"\[\.{3}([a-zA-Z_][\w]*)\]")
  224. # group return the arg name (i.e. "slug")
  225. OPT_CATCHALL = re.compile(r"\[\[\.{3}([a-zA-Z_][\w]*)\]\]")
  226. # 404 variables
  227. ROOT_404 = ""
  228. SLUG_404 = "[..._]"
  229. TITLE_404 = "404 - Not Found"
  230. FAVICON_404 = "favicon.ico"
  231. DESCRIPTION_404 = "The page was not found"
  232. # Color mode variables
  233. USE_COLOR_MODE = "useColorMode"
  234. COLOR_MODE = "colorMode"
  235. TOGGLE_COLOR_MODE = "toggleColorMode"
  236. # Server socket configuration variables
  237. CORS_ALLOWED_ORIGINS = "*"
  238. POLLING_MAX_HTTP_BUFFER_SIZE = 1000 * 1000