Skip to content

Commit 52bbbce

Browse files
committed
hatch fmt
1 parent c8a1740 commit 52bbbce

File tree

17 files changed

+110
-114
lines changed

17 files changed

+110
-114
lines changed

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,9 @@ lint.extend-ignore = [
244244
"S403", # `dill` module is possibly insecure
245245
"S301", # `dill` deserialization is possibly insecure unless using trusted data
246246
"RUF029", # Function is declared async but doesn't contain await expression
247+
"DOC201", # `return` is not documented in docstring
248+
"DOC501", # `Exception` is not documented in docstring
249+
"S308", # Django `mark_safe` may expose cross-site scripting vulnerabilities
247250
]
248251
lint.preview = true
249252
lint.isort.known-first-party = ["reactpy_django", "test_app", "example"]

src/build_scripts/copy_dir.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
# ruff: noqa: INP001
21
import logging
32
import shutil
43
import sys
54
from pathlib import Path
65

6+
logger = logging.getLogger(__name__)
7+
78

89
def copy_files(source: Path, destination: Path) -> None:
910
if destination.exists():
@@ -19,15 +20,15 @@ def copy_files(source: Path, destination: Path) -> None:
1920

2021
if __name__ == "__main__":
2122
if len(sys.argv) != 3:
22-
logging.error("Script used incorrectly!\nUsage: python copy_dir.py <source_dir> <destination>")
23+
logger.error("Script used incorrectly!\nUsage: python copy_dir.py <source_dir> <destination>")
2324
sys.exit(1)
2425

2526
root_dir = Path(__file__).parent.parent.parent
2627
src = Path(root_dir / sys.argv[1])
2728
dest = Path(root_dir / sys.argv[2])
2829

2930
if not src.exists():
30-
logging.error("Source directory %s does not exist", src)
31+
logger.error("Source directory %s does not exist", src)
3132
sys.exit(1)
3233

3334
copy_files(src, dest)

src/reactpy_django/checks.py

Lines changed: 48 additions & 48 deletions
Large diffs are not rendered by default.

src/reactpy_django/components.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
from django.http import HttpRequest
1010
from django.urls import reverse
1111
from reactpy import component, hooks, html, utils
12-
from reactpy.types import Component, Key, VdomDict
1312

1413
from reactpy_django.exceptions import ViewNotRegisteredError
1514
from reactpy_django.forms.components import _django_form
@@ -26,6 +25,7 @@
2625

2726
from django.forms import Form, ModelForm
2827
from django.views import View
28+
from reactpy.types import Component, Key, VdomDict
2929

3030
from reactpy_django.types import AsyncFormEvent, SyncFormEvent, ViewToComponentConstructor, ViewToIframeConstructor
3131

@@ -182,27 +182,27 @@ def _view_to_component(
182182
args: Sequence | None,
183183
kwargs: dict | None,
184184
):
185-
converted_view, set_converted_view = hooks.use_state(cast(Union[VdomDict, None], None))
186-
_args: Sequence = args or ()
187-
_kwargs: dict = kwargs or {}
185+
converted_view, set_converted_view = hooks.use_state(cast("Union[VdomDict, None]", None))
186+
args_: Sequence = args or ()
187+
kwargs_: dict = kwargs or {}
188188
if request:
189-
_request: HttpRequest = request
189+
request_: HttpRequest = request
190190
else:
191-
_request = HttpRequest()
192-
_request.method = "GET"
191+
request_ = HttpRequest()
192+
request_.method = "GET"
193193
resolved_view: Callable = import_module(view) if isinstance(view, str) else view # type: ignore
194194

195195
# Render the view render within a hook
196196
@hooks.use_async_effect(
197197
dependencies=[
198-
json.dumps(vars(_request), default=generate_obj_name),
199-
json.dumps([_args, _kwargs], default=generate_obj_name),
198+
json.dumps(vars(request_), default=generate_obj_name),
199+
json.dumps([args_, kwargs_], default=generate_obj_name),
200200
]
201201
)
202202
async def _render_view():
203203
"""Render the view in an async hook to avoid blocking the main thread."""
204204
# Render the view
205-
response = await render_view(resolved_view, _request, _args, _kwargs)
205+
response = await render_view(resolved_view, request_, args_, kwargs_)
206206
set_converted_view(
207207
utils.string_to_reactpy(
208208
response.content.decode("utf-8").strip(),

src/reactpy_django/forms/components.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def _django_form(
5656
top_children_count = hooks.use_ref(len(top_children))
5757
bottom_children_count = hooks.use_ref(len(bottom_children))
5858
submitted_data, set_submitted_data = hooks.use_state({} or None)
59-
rendered_form, set_rendered_form = hooks.use_state(cast(Union[str, None], None))
59+
rendered_form, set_rendered_form = hooks.use_state(cast("Union[str, None]", None))
6060

6161
# Initialize the form with the provided data
6262
validate_form_args(top_children, top_children_count, bottom_children, bottom_children_count, form)
@@ -70,7 +70,7 @@ def _django_form(
7070
async def render_form():
7171
"""Forms must be rendered in an async loop to allow database fields to execute."""
7272

73-
_logger.debug(f"Rendering form with submitted data: {submitted_data}")
73+
_logger.debug("Rendering form with submitted data: %s", submitted_data)
7474
try:
7575
if submitted_data:
7676
await ensure_async(initialized_form.full_clean, thread_sensitive=thread_sensitive)()
@@ -89,7 +89,6 @@ async def render_form():
8989
except Exception:
9090
_logger.exception("Error during form processing")
9191

92-
9392
async def on_submit_callback(new_data: dict[str, Any]):
9493
"""Callback function provided directly to the client side listener. This is responsible for transmitting
9594
the submitted form data to the server for processing."""

src/reactpy_django/hooks.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import asyncio
44
import logging
55
from collections import defaultdict
6-
from collections.abc import Awaitable
76
from typing import (
87
TYPE_CHECKING,
98
Any,
@@ -39,7 +38,7 @@
3938
from reactpy_django.utils import django_query_postprocessor, ensure_async, generate_obj_name, get_pk
4039

4140
if TYPE_CHECKING:
42-
from collections.abc import Sequence
41+
from collections.abc import Awaitable, Sequence
4342

4443
from channels_redis.core import RedisChannelLayer
4544
from django.contrib.auth.models import AbstractUser
@@ -124,9 +123,9 @@ def use_query(
124123
"""
125124

126125
should_execute, set_should_execute = use_state(True)
127-
data, set_data = use_state(cast(Inferred, None))
126+
data, set_data = use_state(cast("Inferred", None))
128127
loading, set_loading = use_state(True)
129-
error, set_error = use_state(cast(Union[Exception, None], None))
128+
error, set_error = use_state(cast("Union[Exception, None]", None))
130129
query_ref = use_ref(query)
131130
kwargs = kwargs or {}
132131
postprocessor_kwargs = postprocessor_kwargs or {}
@@ -140,14 +139,14 @@ async def execute_query() -> None:
140139
try:
141140
# Run the query
142141
query_async = cast(
143-
Callable[..., Awaitable[Inferred]], ensure_async(query, thread_sensitive=thread_sensitive)
142+
"Callable[..., Awaitable[Inferred]]", ensure_async(query, thread_sensitive=thread_sensitive)
144143
)
145144
new_data = await query_async(**kwargs)
146145

147146
# Run the postprocessor
148147
if postprocessor:
149148
async_postprocessor = cast(
150-
Callable[..., Awaitable[Any]], ensure_async(postprocessor, thread_sensitive=thread_sensitive)
149+
"Callable[..., Awaitable[Any]]", ensure_async(postprocessor, thread_sensitive=thread_sensitive)
151150
)
152151
new_data = await async_postprocessor(new_data, **postprocessor_kwargs)
153152

@@ -227,7 +226,7 @@ def use_mutation(
227226
"""
228227

229228
loading, set_loading = use_state(False)
230-
error, set_error = use_state(cast(Union[Exception, None], None))
229+
error, set_error = use_state(cast("Union[Exception, None]", None))
231230
async_task_refs = use_ref(set())
232231

233232
# The main "running" function for `use_mutation`
@@ -289,7 +288,7 @@ def use_user() -> AbstractUser:
289288

290289

291290
def use_user_data(
292-
default_data: (None | dict[str, Callable[[], Any] | Callable[[], Awaitable[Any]] | Any]) = None,
291+
default_data: (dict[str, Callable[[], Any] | Callable[[], Awaitable[Any]] | Any] | None) = None,
293292
save_default_data: bool = False,
294293
) -> UserData:
295294
"""Get or set user data stored within the REACTPY_DATABASE.
@@ -441,7 +440,7 @@ async def logout(rerender: bool = True) -> None:
441440
return UseAuthTuple(login=login, logout=logout)
442441

443442

444-
async def _get_user_data(user: AbstractUser, default_data: None | dict, save_default_data: bool) -> dict | None:
443+
async def _get_user_data(user: AbstractUser, default_data: dict | None, save_default_data: bool) -> dict | None:
445444
"""The mutation function for `use_user_data`"""
446445
from reactpy_django.models import UserDataModel
447446

src/reactpy_django/router/converters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@
44
CONVERTERS: dict[str, ConversionInfo] = {
55
name: {"regex": converter.regex, "func": converter.to_python} for name, converter in get_converters().items()
66
}
7-
CONVERTERS["any"] = {"regex": r".*", "func": str}
7+
CONVERTERS["any"] = {"regex": r".*", "func": str}
Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,10 @@
11
from __future__ import annotations
22

3-
from django.urls.converters import get_converters
4-
5-
from typing import TYPE_CHECKING
6-
73
from reactpy_router.resolvers import ReactPyResolver
84

95
from reactpy_django.router.converters import CONVERTERS
106

11-
if TYPE_CHECKING:
12-
from reactpy_router.types import Route
13-
147

158
class DjangoResolver(ReactPyResolver):
16-
"""A simple route resolver that uses regex to match paths"""
17-
param_pattern=r"<(?P<type>\w+:)?(?P<name>\w+)>"
9+
param_pattern = r"<(?P<type>\w+:)?(?P<name>\w+)>"
1810
converters = CONVERTERS

src/reactpy_django/templatetags/reactpy.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ def component(
9494
class_ = kwargs.pop("class", "")
9595
has_args = bool(args or kwargs)
9696
user_component: ComponentConstructor | None = None
97-
_prerender_html = ""
98-
_offline_html = ""
97+
prerender_html = ""
98+
offline_html = ""
9999

100100
# Validate the host
101101
if host and DJANGO_DEBUG:
@@ -151,7 +151,7 @@ def component(
151151
)
152152
_logger.error(msg)
153153
return failure_context(dotted_path, ComponentCarrierError(msg))
154-
_prerender_html = prerender_component(user_component, args, kwargs, uuid, request)
154+
prerender_html = prerender_component(user_component, args, kwargs, uuid, request)
155155

156156
# Fetch the offline component's HTML, if requested
157157
if offline:
@@ -167,7 +167,7 @@ def component(
167167
)
168168
_logger.error(msg)
169169
return failure_context(dotted_path, ComponentCarrierError(msg))
170-
_offline_html = prerender_component(offline_component, [], {}, uuid, request)
170+
offline_html = prerender_component(offline_component, [], {}, uuid, request)
171171

172172
# Return the template rendering context
173173
return {
@@ -181,10 +181,11 @@ def component(
181181
"reactpy_reconnect_max_interval": reactpy_config.REACTPY_RECONNECT_MAX_INTERVAL,
182182
"reactpy_reconnect_backoff_multiplier": reactpy_config.REACTPY_RECONNECT_BACKOFF_MULTIPLIER,
183183
"reactpy_reconnect_max_retries": reactpy_config.REACTPY_RECONNECT_MAX_RETRIES,
184-
"reactpy_prerender_html": mark_safe(_prerender_html),
185-
"reactpy_offline_html": mark_safe(_offline_html),
184+
"reactpy_prerender_html": mark_safe(prerender_html),
185+
"reactpy_offline_html": mark_safe(offline_html),
186186
}
187187

188+
188189
@register.inclusion_tag("reactpy/pyscript_component.html", takes_context=True)
189190
def pyscript_component(
190191
context: template.RequestContext,

src/reactpy_django/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -453,7 +453,7 @@ def save_component_params(args, kwargs, uuid) -> None:
453453
def validate_host(host: str) -> None:
454454
"""Validates the host string to ensure it does not contain a protocol."""
455455
if "://" in host:
456-
protocol = host.split("://")[0]
456+
protocol = host.split("://", maxsplit=1)[0]
457457
msg = f"Invalid host provided to component. Contains a protocol '{protocol}://'."
458458
_logger.error(msg)
459459
raise InvalidHostError(msg)

0 commit comments

Comments
 (0)