Skip to content

Commit

Permalink
Fix project hash and modernize type annotations (#1704)
Browse files Browse the repository at this point in the history
  • Loading branch information
picklelo authored Sep 1, 2023
1 parent 9786913 commit 1d9f25b
Show file tree
Hide file tree
Showing 22 changed files with 160 additions and 154 deletions.
5 changes: 2 additions & 3 deletions reflex/.templates/web/utils/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ import Router, { useRouter } from "next/router";


// Endpoint URLs.
const PINGURL = env.pingUrl
const EVENTURL = env.eventUrl
const UPLOADURL = env.uploadUrl
const EVENTURL = env.EVENT
const UPLOADURL = env.UPLOAD

// Global variable to hold the token.
let token;
Expand Down
35 changes: 18 additions & 17 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
Dict,
List,
Optional,
Tuple,
Type,
Union,
)
Expand Down Expand Up @@ -210,7 +209,7 @@ def add_cors(self):
allow_origins=["*"],
)

async def preprocess(self, state: State, event: Event) -> Optional[StateUpdate]:
async def preprocess(self, state: State, event: Event) -> StateUpdate | None:
"""Preprocess the event.
This is where middleware can modify the event before it is processed.
Expand Down Expand Up @@ -263,7 +262,7 @@ async def postprocess(
return out # type: ignore
return update

def add_middleware(self, middleware: Middleware, index: Optional[int] = None):
def add_middleware(self, middleware: Middleware, index: int | None = None):
"""Add middleware to the app.
Args:
Expand Down Expand Up @@ -302,16 +301,17 @@ def _generate_component(component: Component | ComponentCallable) -> Component:

def add_page(
self,
component: Union[Component, ComponentCallable],
route: Optional[str] = None,
component: Component | ComponentCallable,
route: str | None = None,
title: str = constants.DEFAULT_TITLE,
description: str = constants.DEFAULT_DESCRIPTION,
image=constants.DEFAULT_IMAGE,
on_load: Optional[
Union[EventHandler, EventSpec, List[Union[EventHandler, EventSpec]]]
] = None,
meta: List[Dict] = constants.DEFAULT_META_LIST,
script_tags: Optional[List[Component]] = None,
on_load: EventHandler
| EventSpec
| list[EventHandler | EventSpec]
| None = None,
meta: list[dict[str, str]] = constants.DEFAULT_META_LIST,
script_tags: list[Component] | None = None,
):
"""Add a page to the app.
Expand Down Expand Up @@ -379,7 +379,7 @@ def add_page(
on_load = [on_load]
self.load_events[route] = on_load

def get_load_events(self, route: str) -> List[Union[EventHandler, EventSpec]]:
def get_load_events(self, route: str) -> list[EventHandler | EventSpec]:
"""Get the load events for a route.
Args:
Expand Down Expand Up @@ -428,14 +428,15 @@ def _check_routes_conflict(self, new_route: str):

def add_custom_404_page(
self,
component: Optional[Union[Component, ComponentCallable]] = None,
component: Component | ComponentCallable | None = None,
title: str = constants.TITLE_404,
image: str = constants.FAVICON_404,
description: str = constants.DESCRIPTION_404,
on_load: Optional[
Union[EventHandler, EventSpec, List[Union[EventHandler, EventSpec]]]
] = None,
meta: List[Dict] = constants.DEFAULT_META_LIST,
on_load: EventHandler
| EventSpec
| list[EventHandler | EventSpec]
| None = None,
meta: list[dict[str, str]] = constants.DEFAULT_META_LIST,
):
"""Define a custom 404 page for any url having no match.
Expand Down Expand Up @@ -694,7 +695,7 @@ async def upload_file(files: List[UploadFile]):
# get the current state(parent state/substate)
path = handler.split(".")[:-1]
current_state = state.get_substate(path)
handler_upload_param: Tuple = ()
handler_upload_param = ()

# get handler function
func = getattr(current_state, handler.split(".")[-1])
Expand Down
4 changes: 2 additions & 2 deletions reflex/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Define the base Reflex class."""
from __future__ import annotations

from typing import Any, Dict
from typing import Any

import pydantic
from pydantic.fields import ModelField
Expand Down Expand Up @@ -46,7 +46,7 @@ def set(self, **kwargs):
return self

@classmethod
def get_fields(cls) -> Dict[str, Any]:
def get_fields(cls) -> dict[str, Any]:
"""Get the fields of the object.
Returns:
Expand Down
6 changes: 4 additions & 2 deletions reflex/components/base/meta.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Display the title of the current page."""

from typing import Dict, Optional
from __future__ import annotations

from typing import Optional

from reflex.components.base.bare import Bare
from reflex.components.component import Component
Expand All @@ -11,7 +13,7 @@ class Title(Component):

tag = "title"

def render(self) -> Dict:
def render(self) -> dict:
"""Render the title component.
Returns:
Expand Down
4 changes: 2 additions & 2 deletions reflex/components/base/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
https://nextjs.org/docs/app/api-reference/components/script
"""
from typing import Set
from __future__ import annotations

from reflex.components.component import Component
from reflex.event import EventChain
Expand Down Expand Up @@ -57,7 +57,7 @@ def create(cls, *children, **props) -> Component:
raise ValueError("Must provide inline script or `src` prop.")
return super().create(*children, **props)

def get_triggers(self) -> Set[str]:
def get_triggers(self) -> set[str]:
"""Get the event triggers for the component.
Returns:
Expand Down
14 changes: 7 additions & 7 deletions reflex/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ def postgresql(
cls,
database: str,
username: str,
password: Optional[str] = None,
host: Optional[str] = None,
port: Optional[int] = 5432,
password: str | None = None,
host: str | None = None,
port: int | None = 5432,
) -> DBConfig:
"""Create an instance with postgresql engine.
Expand Down Expand Up @@ -58,9 +58,9 @@ def postgresql_psycopg2(
cls,
database: str,
username: str,
password: Optional[str] = None,
host: Optional[str] = None,
port: Optional[int] = 5432,
password: str | None = None,
host: str | None = None,
port: int | None = 5432,
) -> DBConfig:
"""Create an instance with postgresql+psycopg2 engine.
Expand Down Expand Up @@ -259,7 +259,7 @@ def update_from_env(self):
# Set the value.
setattr(self, key, env_var)

def get_event_namespace(self) -> Optional[str]:
def get_event_namespace(self) -> str | None:
"""Get the websocket event namespace.
Returns:
Expand Down
3 changes: 1 addition & 2 deletions reflex/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import re
from enum import Enum
from types import SimpleNamespace
from typing import Optional

from platformdirs import PlatformDirs

Expand All @@ -19,7 +18,7 @@
IS_WINDOWS = platform.system() == "Windows"


def get_fnm_name() -> Optional[str]:
def get_fnm_name() -> str | None:
"""Get the appropriate fnm executable name based on the current platform.
Returns:
Expand Down
20 changes: 9 additions & 11 deletions reflex/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from __future__ import annotations

import inspect
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
from typing import Any, Callable, Dict, List, Tuple

from reflex import constants
from reflex.base import Base
Expand Down Expand Up @@ -162,7 +162,7 @@ def fn():
)


def redirect(path: Union[str, Var[str]]) -> EventSpec:
def redirect(path: str | Var[str]) -> EventSpec:
"""Redirect to a new path.
Args:
Expand All @@ -174,7 +174,7 @@ def redirect(path: Union[str, Var[str]]) -> EventSpec:
return server_side("_redirect", get_fn_signature(redirect), path=path)


def console_log(message: Union[str, Var[str]]) -> EventSpec:
def console_log(message: str | Var[str]) -> EventSpec:
"""Do a console.log on the browser.
Args:
Expand All @@ -186,7 +186,7 @@ def console_log(message: Union[str, Var[str]]) -> EventSpec:
return server_side("_console", get_fn_signature(console_log), message=message)


def window_alert(message: Union[str, Var[str]]) -> EventSpec:
def window_alert(message: str | Var[str]) -> EventSpec:
"""Create a window alert on the browser.
Args:
Expand Down Expand Up @@ -250,7 +250,7 @@ def set_cookie(key: str, value: str) -> EventSpec:
)


def remove_cookie(key: str, options: Dict[str, Any] = {}) -> EventSpec: # noqa: B006
def remove_cookie(key: str, options: dict[str, Any] = {}) -> EventSpec: # noqa: B006
"""Remove a cookie on the frontend.
Args:
Expand Down Expand Up @@ -378,7 +378,7 @@ def call_event_handler(event_handler: EventHandler, arg: Var) -> EventSpec:
return event_handler(arg)


def call_event_fn(fn: Callable, arg: Var) -> List[EventSpec]:
def call_event_fn(fn: Callable, arg: Var) -> list[EventSpec]:
"""Call a function to a list of event specs.
The function should return either a single EventSpec or a list of EventSpecs.
Expand Down Expand Up @@ -434,7 +434,7 @@ def call_event_fn(fn: Callable, arg: Var) -> List[EventSpec]:
return events


def get_handler_args(event_spec: EventSpec, arg: Var) -> Tuple[Tuple[Var, Var], ...]:
def get_handler_args(event_spec: EventSpec, arg: Var) -> tuple[tuple[Var, Var], ...]:
"""Get the handler args for the given event spec.
Args:
Expand All @@ -449,9 +449,7 @@ def get_handler_args(event_spec: EventSpec, arg: Var) -> Tuple[Tuple[Var, Var],
return event_spec.args if len(args) > 1 else tuple()


def fix_events(
events: Optional[List[Union[EventHandler, EventSpec]]], token: str
) -> List[Event]:
def fix_events(events: list[EventHandler | EventSpec], token: str) -> list[Event]:
"""Fix a list of events returned by an event handler.
Args:
Expand Down Expand Up @@ -510,7 +508,7 @@ def get_fn_signature(fn: Callable) -> inspect.Signature:


# A set of common event triggers.
EVENT_TRIGGERS: Set[str] = {
EVENT_TRIGGERS: set[str] = {
"on_focus",
"on_blur",
"on_click",
Expand Down
10 changes: 6 additions & 4 deletions reflex/model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Database built into Reflex."""

from __future__ import annotations

import os
from collections import defaultdict
from pathlib import Path
Expand All @@ -21,7 +23,7 @@
from reflex.utils import console


def get_engine(url: Optional[str] = None):
def get_engine(url: str | None = None):
"""Get the database engine.
Args:
Expand Down Expand Up @@ -142,7 +144,7 @@ def alembic_init(cls):
def alembic_autogenerate(
cls,
connection: sqlalchemy.engine.Connection,
message: Optional[str] = None,
message: str | None = None,
write_migration_scripts: bool = True,
) -> bool:
"""Generate migration scripts for alembic-detectable changes.
Expand Down Expand Up @@ -233,7 +235,7 @@ def run_upgrade(rev, context):
env.run_migrations()

@classmethod
def migrate(cls, autogenerate: bool = False) -> Optional[bool]:
def migrate(cls, autogenerate: bool = False) -> bool | None:
"""Execute alembic migrations for all sqlmodel Model classes.
If alembic is not installed or has not been initialized for the project,
Expand Down Expand Up @@ -277,7 +279,7 @@ def select(cls):
return sqlmodel.select(cls)


def session(url: Optional[str] = None) -> sqlmodel.Session:
def session(url: str | None = None) -> sqlmodel.Session:
"""Get a session to interact with the database.
Args:
Expand Down
17 changes: 7 additions & 10 deletions reflex/page.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,20 @@

from __future__ import annotations

from typing import List, Optional, Union

from reflex.components.component import Component
from reflex.event import EventHandler

DECORATED_PAGES = []


def page(
route: Optional[str] = None,
title: Optional[str] = None,
image: Optional[str] = None,
description: Optional[str] = None,
meta: Optional[str] = None,
script_tags: Optional[List[Component]] = None,
on_load: Optional[Union[EventHandler, List[EventHandler]]] = None,
route: str | None = None,
title: str | None = None,
image: str | None = None,
description: str | None = None,
meta: str | None = None,
script_tags: list[Component] | None = None,
on_load: EventHandler | list[EventHandler] | None = None,
):
"""Decorate a function as a page.
Expand All @@ -40,7 +38,6 @@ def page(
Returns:
The decorated function.
"""
...

def decorator(render_fn):
kwargs = {}
Expand Down
1 change: 0 additions & 1 deletion reflex/reflex.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ def init(
if not os.path.exists(constants.CONFIG_FILE):
prerequisites.create_config(app_name)
prerequisites.initialize_app_directory(app_name, template)
build.set_reflex_project_hash()
telemetry.send("init", config.telemetry_enabled)
else:
telemetry.send("reinit", config.telemetry_enabled)
Expand Down
Loading

0 comments on commit 1d9f25b

Please sign in to comment.