move a bit more

This commit is contained in:
Khaleel Al-Adhami 2024-10-16 17:37:10 -07:00
parent 0308912386
commit a9b7c284e7
9 changed files with 29 additions and 37 deletions

View File

@ -2,13 +2,13 @@
from __future__ import annotations from __future__ import annotations
import os
from pathlib import Path from pathlib import Path
from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple
from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf from reflex.components.component import Component, ComponentNamespace, MemoizationLeaf
from reflex.components.el.elements.forms import Input from reflex.components.el.elements.forms import Input
from reflex.components.radix.themes.layout.box import Box from reflex.components.radix.themes.layout.box import Box
from reflex.config import environment
from reflex.constants import Dirs from reflex.constants import Dirs
from reflex.event import ( from reflex.event import (
CallableEventSpec, CallableEventSpec,
@ -125,9 +125,7 @@ def get_upload_dir() -> Path:
""" """
Upload.is_used = True Upload.is_used = True
uploaded_files_dir = Path( uploaded_files_dir = environment.REFLEX_UPLOADED_FILES_DIR
os.environ.get("REFLEX_UPLOADED_FILES_DIR", "./uploaded_files")
)
uploaded_files_dir.mkdir(parents=True, exist_ok=True) uploaded_files_dir.mkdir(parents=True, exist_ok=True)
return uploaded_files_dir return uploaded_files_dir

View File

@ -169,8 +169,8 @@ def interpret_boolean_env(value: str) -> bool:
Raises: Raises:
ValueError: If the value is invalid. ValueError: If the value is invalid.
""" """
true_values = ["true", "1", "yes"] true_values = ["true", "1", "yes", "y"]
false_values = ["false", "0", "no"] false_values = ["false", "0", "no", "n"]
if value.lower() in true_values: if value.lower() in true_values:
return True return True
@ -250,6 +250,15 @@ class EnvironmentVariables:
# The working directory for the next.js commands. # The working directory for the next.js commands.
REFLEX_WEB_WORKDIR: Path = Path(constants.Dirs.WEB) REFLEX_WEB_WORKDIR: Path = Path(constants.Dirs.WEB)
# Path to the alembic config file
ALEMBIC_CONFIG: Path = Path(constants.ALEMBIC_CONFIG)
# Disable SSL verification for HTTPX requests.
SSL_NO_VERIFY: bool = False
# The directory to store uploaded files.
REFLEX_UPLOADED_FILES_DIR: Path = Path(constants.Dirs.UPLOADED_FILES)
def __init__(self): def __init__(self):
"""Initialize the environment variables.""" """Initialize the environment variables."""
type_hints = get_type_hints(type(self)) type_hints = get_type_hints(type(self))

View File

@ -20,6 +20,8 @@ class Dirs(SimpleNamespace):
# The frontend directories in a project. # The frontend directories in a project.
# The web folder where the NextJS app is compiled to. # The web folder where the NextJS app is compiled to.
WEB = ".web" WEB = ".web"
# The directory where uploaded files are stored.
UPLOADED_FILES = "uploaded_files"
# The name of the assets directory. # The name of the assets directory.
APP_ASSETS = "assets" APP_ASSETS = "assets"
# The name of the assets directory for external ressource (a subfolder of APP_ASSETS). # The name of the assets directory for external ressource (a subfolder of APP_ASSETS).

View File

@ -1,6 +1,5 @@
"""Config constants.""" """Config constants."""
import os
from pathlib import Path from pathlib import Path
from types import SimpleNamespace from types import SimpleNamespace
@ -9,7 +8,7 @@ from reflex.constants.base import Dirs, Reflex
from .compiler import Ext from .compiler import Ext
# Alembic migrations # Alembic migrations
ALEMBIC_CONFIG = os.environ.get("ALEMBIC_CONFIG", "alembic.ini") ALEMBIC_CONFIG = "alembic.ini"
class Config(SimpleNamespace): class Config(SimpleNamespace):

View File

@ -4,7 +4,6 @@ from __future__ import annotations
import os import os
from collections import defaultdict from collections import defaultdict
from pathlib import Path
from typing import Any, ClassVar, Optional, Type, Union from typing import Any, ClassVar, Optional, Type, Union
import alembic.autogenerate import alembic.autogenerate
@ -18,9 +17,8 @@ import sqlalchemy
import sqlalchemy.exc import sqlalchemy.exc
import sqlalchemy.orm import sqlalchemy.orm
from reflex import constants
from reflex.base import Base from reflex.base import Base
from reflex.config import get_config from reflex.config import environment, get_config
from reflex.utils import console from reflex.utils import console
from reflex.utils.compat import sqlmodel, sqlmodel_field_has_primary_key from reflex.utils.compat import sqlmodel, sqlmodel_field_has_primary_key
@ -41,7 +39,7 @@ def get_engine(url: str | None = None) -> sqlalchemy.engine.Engine:
url = url or conf.db_url url = url or conf.db_url
if url is None: if url is None:
raise ValueError("No database url configured") raise ValueError("No database url configured")
if not Path(constants.ALEMBIC_CONFIG).exists(): if environment.ALEMBIC_CONFIG.exists():
console.warn( console.warn(
"Database is not initialized, run [bold]reflex db init[/bold] first." "Database is not initialized, run [bold]reflex db init[/bold] first."
) )
@ -234,7 +232,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
Returns: Returns:
tuple of (config, script_directory) tuple of (config, script_directory)
""" """
config = alembic.config.Config(constants.ALEMBIC_CONFIG) config = alembic.config.Config(environment.ALEMBIC_CONFIG)
return config, alembic.script.ScriptDirectory( return config, alembic.script.ScriptDirectory(
config.get_main_option("script_location", default="version"), config.get_main_option("script_location", default="version"),
) )
@ -269,8 +267,8 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
def alembic_init(cls): def alembic_init(cls):
"""Initialize alembic for the project.""" """Initialize alembic for the project."""
alembic.command.init( alembic.command.init(
config=alembic.config.Config(constants.ALEMBIC_CONFIG), config=alembic.config.Config(environment.ALEMBIC_CONFIG),
directory=str(Path(constants.ALEMBIC_CONFIG).parent / "alembic"), directory=str(environment.ALEMBIC_CONFIG.parent / "alembic"),
) )
@classmethod @classmethod
@ -290,7 +288,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
Returns: Returns:
True when changes have been detected. True when changes have been detected.
""" """
if not Path(constants.ALEMBIC_CONFIG).exists(): if not environment.ALEMBIC_CONFIG.exists():
return False return False
config, script_directory = cls._alembic_config() config, script_directory = cls._alembic_config()
@ -391,7 +389,7 @@ class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssue
True - indicating the process was successful. True - indicating the process was successful.
None - indicating the process was skipped. None - indicating the process was skipped.
""" """
if not Path(constants.ALEMBIC_CONFIG).exists(): if not environment.ALEMBIC_CONFIG.exists():
return return
with cls.get_db_engine().connect() as connection: with cls.get_db_engine().connect() as connection:

View File

@ -13,7 +13,7 @@ from reflex_cli.deployments import deployments_cli
from reflex_cli.utils import dependency from reflex_cli.utils import dependency
from reflex import constants from reflex import constants
from reflex.config import get_config from reflex.config import environment, get_config
from reflex.custom_components.custom_components import custom_components_cli from reflex.custom_components.custom_components import custom_components_cli
from reflex.state import reset_disk_state_manager from reflex.state import reset_disk_state_manager
from reflex.utils import console, redir, telemetry from reflex.utils import console, redir, telemetry
@ -406,7 +406,7 @@ def db_init():
return return
# Check the alembic config. # Check the alembic config.
if Path(constants.ALEMBIC_CONFIG).exists(): if environment.ALEMBIC_CONFIG.exists():
console.error( console.error(
"Database is already initialized. Use " "Database is already initialized. Use "
"[bold]reflex db makemigrations[/bold] to create schema change " "[bold]reflex db makemigrations[/bold] to create schema change "

View File

@ -23,18 +23,6 @@ def set_env_json():
) )
def set_os_env(**kwargs):
"""Set os environment variables.
Args:
kwargs: env key word args.
"""
for key, value in kwargs.items():
if not value:
continue
os.environ[key.upper()] = value
def generate_sitemap_config(deploy_url: str, export=False): def generate_sitemap_config(deploy_url: str, export=False):
"""Generate the sitemap config file. """Generate the sitemap config file.

View File

@ -1,9 +1,8 @@
"""Helpers for downloading files from the network.""" """Helpers for downloading files from the network."""
import os
import httpx import httpx
from ..config import environment
from . import console from . import console
@ -13,8 +12,7 @@ def _httpx_verify_kwarg() -> bool:
Returns: Returns:
True if SSL verification is enabled, False otherwise True if SSL verification is enabled, False otherwise
""" """
ssl_no_verify = os.environ.get("SSL_NO_VERIFY", "").lower() in ["true", "1", "yes"] return not environment.SSL_NO_VERIFY
return not ssl_no_verify
def get(url: str, **kwargs) -> httpx.Response: def get(url: str, **kwargs) -> httpx.Response:

View File

@ -1144,7 +1144,7 @@ def check_db_initialized() -> bool:
Returns: Returns:
True if alembic is initialized (or if database is not used). True if alembic is initialized (or if database is not used).
""" """
if get_config().db_url is not None and not Path(constants.ALEMBIC_CONFIG).exists(): if get_config().db_url is not None and not environment.ALEMBIC_CONFIG.exists():
console.error( console.error(
"Database is not initialized. Run [bold]reflex db init[/bold] first." "Database is not initialized. Run [bold]reflex db init[/bold] first."
) )
@ -1154,7 +1154,7 @@ def check_db_initialized() -> bool:
def check_schema_up_to_date(): def check_schema_up_to_date():
"""Check if the sqlmodel metadata matches the current database schema.""" """Check if the sqlmodel metadata matches the current database schema."""
if get_config().db_url is None or not Path(constants.ALEMBIC_CONFIG).exists(): if get_config().db_url is None or not environment.ALEMBIC_CONFIG.exists():
return return
with model.Model.get_db_engine().connect() as connection: with model.Model.get_db_engine().connect() as connection:
try: try: