Skip to content

Commit b1e2f59

Browse files
committed
misc pylint refactoring
1 parent 24873ee commit b1e2f59

File tree

3 files changed

+34
-22
lines changed

3 files changed

+34
-22
lines changed

src/reactpy_django/hooks.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,8 @@ def use_connection() -> ConnectionType:
103103

104104
def use_query(
105105
query: Callable[FuncParams, Awaitable[Inferred]] | Callable[FuncParams, Inferred],
106-
*,
107106
kwargs: dict[str, Any] | None = None,
107+
*,
108108
thread_sensitive: bool = True,
109109
postprocessor: (
110110
AsyncPostprocessor | SyncPostprocessor | None
@@ -116,6 +116,8 @@ def use_query(
116116
117117
Args:
118118
query: A callable that returns a Django `Model` or `QuerySet`.
119+
120+
Kwargs:
119121
kwargs: Keyword arguments to passed into the `query` function.
120122
thread_sensitive: Whether to run the query in thread-sensitive mode. \
121123
This setting only applies to sync query functions.
@@ -153,8 +155,7 @@ async def execute_query() -> None:
153155
new_data = await query(**kwargs)
154156
else:
155157
new_data = await database_sync_to_async(
156-
query,
157-
thread_sensitive=thread_sensitive,
158+
query, thread_sensitive=thread_sensitive
158159
)(**kwargs)
159160

160161
# Run the postprocessor
@@ -171,7 +172,7 @@ async def execute_query() -> None:
171172
set_data(cast(Inferred, None))
172173
set_loading(False)
173174
set_error(e)
174-
_logger.exception(f"Failed to execute query: {generate_obj_name(query)}")
175+
_logger.exception("Failed to execute query: %s", generate_obj_name(query))
175176
return
176177

177178
# Query was successful
@@ -228,6 +229,8 @@ def use_mutation(
228229
mutation: A callable that performs Django ORM create, update, or delete \
229230
functionality. If this function returns `False`, then your `refetch` \
230231
function will not be used.
232+
233+
Kwargs:
231234
thread_sensitive: Whether to run the mutation in thread-sensitive mode. \
232235
This setting only applies to sync mutation functions.
233236
refetch: A query function (the function you provide to your `use_query` \
@@ -259,7 +262,7 @@ async def execute_mutation(exec_args, exec_kwargs) -> None:
259262
set_loading(False)
260263
set_error(e)
261264
_logger.exception(
262-
f"Failed to execute mutation: {generate_obj_name(mutation)}"
265+
"Failed to execute mutation: %s", generate_obj_name(mutation)
263266
)
264267

265268
# Mutation was successful

src/reactpy_django/utils.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,19 @@
2929
)
3030

3131
_logger = logging.getLogger(__name__)
32-
_component_tag = r"(?P<tag>component)"
33-
_component_path = r"""(?P<path>"[^"'\s]+"|'[^"'\s]+')"""
34-
_component_offline_kwarg = (
35-
rf"""(\s*offline\s*=\s*{_component_path.replace(r"<path>", r"<offline_path>")})"""
32+
_TAG_PATTERN = r"(?P<tag>component)"
33+
_PATH_PATTERN = r"""(?P<path>"[^"'\s]+"|'[^"'\s]+')"""
34+
_OFFLINE_KWARG_PATTERN = (
35+
rf"""(\s*offline\s*=\s*{_PATH_PATTERN.replace(r"<path>", r"<offline_path>")})"""
3636
)
37-
_component_generic_kwarg = r"""(\s*.*?)"""
37+
_GENERIC_KWARG_PATTERN = r"""(\s*.*?)"""
3838
COMMENT_REGEX = re.compile(r"<!--[\s\S]*?-->")
3939
COMPONENT_REGEX = re.compile(
4040
r"{%\s*"
41-
+ _component_tag
41+
+ _TAG_PATTERN
4242
+ r"\s*"
43-
+ _component_path
44-
+ rf"({_component_offline_kwarg}|{_component_generic_kwarg})*?"
43+
+ _PATH_PATTERN
44+
+ rf"({_OFFLINE_KWARG_PATTERN}|{_GENERIC_KWARG_PATTERN})*?"
4545
+ r"\s*%}"
4646
)
4747

@@ -380,4 +380,4 @@ def strtobool(val):
380380
elif val in ("n", "no", "f", "false", "off", "0"):
381381
return 0
382382
else:
383-
raise ValueError("invalid truth value %r" % (val,))
383+
raise ValueError(f"invalid truth value {val}")

src/reactpy_django/websocket/consumer.py

+17-8
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@
2929
if TYPE_CHECKING:
3030
from django.contrib.auth.models import AbstractUser
3131

32+
from reactpy_django import models
33+
3234
_logger = logging.getLogger(__name__)
3335
BACKHAUL_LOOP = asyncio.new_event_loop()
3436

@@ -47,9 +49,18 @@ def start_backhaul_loop():
4749
class ReactpyAsyncWebsocketConsumer(AsyncJsonWebsocketConsumer):
4850
"""Communicates with the browser to perform actions on-demand."""
4951

52+
def __init__(self, *args, **kwargs):
53+
super().__init__(*args, **kwargs)
54+
55+
# New WebsocketConsumer attributes created by ReactPy
56+
self.dispatcher: Future | asyncio.Task
57+
self.threaded: bool
58+
self.recv_queue: asyncio.Queue
59+
self.dotted_path: str
60+
self.component_session: "models.ComponentSession" | None = None
61+
5062
async def connect(self) -> None:
5163
"""The browser has connected."""
52-
from reactpy_django import models
5364
from reactpy_django.config import (
5465
REACTPY_AUTH_BACKEND,
5566
REACTPY_AUTO_RELOGIN,
@@ -79,9 +90,7 @@ async def connect(self) -> None:
7990
)
8091

8192
# Start the component dispatcher
82-
self.dispatcher: Future | asyncio.Task
8393
self.threaded = REACTPY_BACKHAUL_THREAD
84-
self.component_session: models.ComponentSession | None = None
8594
if self.threaded:
8695
if not BACKHAUL_THREAD.is_alive():
8796
await asyncio.to_thread(
@@ -149,14 +158,14 @@ async def run_dispatcher(self):
149158
)
150159

151160
scope = self.scope
152-
self.dotted_path = dotted_path = scope["url_route"]["kwargs"]["dotted_path"]
161+
self.dotted_path = scope["url_route"]["kwargs"]["dotted_path"]
153162
uuid = scope["url_route"]["kwargs"].get("uuid")
154163
has_args = scope["url_route"]["kwargs"].get("has_args")
155164
scope["reactpy"] = {"id": str(uuid)}
156165
query_string = parse_qs(scope["query_string"].decode(), strict_parsing=True)
157166
http_pathname = query_string.get("http_pathname", [""])[0]
158167
http_search = query_string.get("http_search", [""])[0]
159-
self.recv_queue: asyncio.Queue = asyncio.Queue()
168+
self.recv_queue = asyncio.Queue()
160169
connection = Connection( # For `use_connection`
161170
scope=scope,
162171
location=Location(pathname=http_pathname, search=http_search),
@@ -168,11 +177,11 @@ async def run_dispatcher(self):
168177

169178
# Verify the component has already been registered
170179
try:
171-
root_component_constructor = REACTPY_REGISTERED_COMPONENTS[dotted_path]
180+
root_component_constructor = REACTPY_REGISTERED_COMPONENTS[self.dotted_path]
172181
except KeyError:
173182
await asyncio.to_thread(
174183
_logger.warning,
175-
f"Attempt to access invalid ReactPy component: {dotted_path!r}",
184+
f"Attempt to access invalid ReactPy component: {self.dotted_path!r}",
176185
)
177186
return
178187

@@ -194,7 +203,7 @@ async def run_dispatcher(self):
194203
except models.ComponentSession.DoesNotExist:
195204
await asyncio.to_thread(
196205
_logger.warning,
197-
f"Component session for '{dotted_path}:{uuid}' not found. The "
206+
f"Component session for '{self.dotted_path}:{uuid}' not found. The "
198207
"session may have already expired beyond REACTPY_SESSION_MAX_AGE. "
199208
"If you are using a custom `host`, you may have forgotten to provide "
200209
"args/kwargs.",

0 commit comments

Comments
 (0)