reactpy_django 3.8.1__py2.py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- js/node_modules/flatted/python/flatted.py +149 -0
- js/node_modules/flatted/python/test.py +63 -0
- reactpy_django/__init__.py +28 -0
- reactpy_django/apps.py +11 -0
- reactpy_django/checks.py +542 -0
- reactpy_django/clean.py +141 -0
- reactpy_django/components.py +286 -0
- reactpy_django/config.py +135 -0
- reactpy_django/database.py +31 -0
- reactpy_django/decorators.py +101 -0
- reactpy_django/exceptions.py +34 -0
- reactpy_django/hooks.py +496 -0
- reactpy_django/http/__init__.py +0 -0
- reactpy_django/http/urls.py +18 -0
- reactpy_django/http/views.py +62 -0
- reactpy_django/management/__init__.py +0 -0
- reactpy_django/management/commands/__init__.py +0 -0
- reactpy_django/management/commands/clean_reactpy.py +37 -0
- reactpy_django/migrations/0001_initial.py +25 -0
- reactpy_django/migrations/0002_rename_created_at_componentparams_last_accessed.py +17 -0
- reactpy_django/migrations/0003_componentsession_delete_componentparams.py +28 -0
- reactpy_django/migrations/0004_config.py +27 -0
- reactpy_django/migrations/0005_alter_componentsession_last_accessed.py +17 -0
- reactpy_django/migrations/0006_userdatamodel.py +28 -0
- reactpy_django/migrations/__init__.py +0 -0
- reactpy_django/models.py +48 -0
- reactpy_django/py.typed +1 -0
- reactpy_django/router/__init__.py +5 -0
- reactpy_django/router/converters.py +7 -0
- reactpy_django/router/resolvers.py +58 -0
- reactpy_django/static/reactpy_django/client.js +1630 -0
- reactpy_django/templates/reactpy/component.html +27 -0
- reactpy_django/templatetags/__init__.py +0 -0
- reactpy_django/templatetags/reactpy.py +221 -0
- reactpy_django/types.py +121 -0
- reactpy_django/utils.py +384 -0
- reactpy_django/websocket/__init__.py +0 -0
- reactpy_django/websocket/consumer.py +218 -0
- reactpy_django/websocket/paths.py +17 -0
- reactpy_django-3.8.1.dist-info/LICENSE.md +9 -0
- reactpy_django-3.8.1.dist-info/METADATA +152 -0
- reactpy_django-3.8.1.dist-info/RECORD +44 -0
- reactpy_django-3.8.1.dist-info/WHEEL +6 -0
- reactpy_django-3.8.1.dist-info/top_level.txt +2 -0
reactpy_django/utils.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import inspect
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
from asyncio import iscoroutinefunction
|
|
9
|
+
from fnmatch import fnmatch
|
|
10
|
+
from importlib import import_module
|
|
11
|
+
from typing import Any, Callable, Sequence
|
|
12
|
+
|
|
13
|
+
from asgiref.sync import async_to_sync
|
|
14
|
+
from channels.db import database_sync_to_async
|
|
15
|
+
from django.db.models import ManyToManyField, ManyToOneRel, prefetch_related_objects
|
|
16
|
+
from django.db.models.base import Model
|
|
17
|
+
from django.db.models.query import QuerySet
|
|
18
|
+
from django.http import HttpRequest, HttpResponse
|
|
19
|
+
from django.template import engines
|
|
20
|
+
from django.utils.encoding import smart_str
|
|
21
|
+
from django.views import View
|
|
22
|
+
from reactpy.core.layout import Layout
|
|
23
|
+
from reactpy.types import ComponentConstructor
|
|
24
|
+
|
|
25
|
+
from reactpy_django.exceptions import (
|
|
26
|
+
ComponentDoesNotExistError,
|
|
27
|
+
ComponentParamError,
|
|
28
|
+
ViewDoesNotExistError,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
_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>")})"""
|
|
36
|
+
)
|
|
37
|
+
_component_generic_kwarg = r"""(\s*.*?)"""
|
|
38
|
+
COMMENT_REGEX = re.compile(r"<!--[\s\S]*?-->")
|
|
39
|
+
COMPONENT_REGEX = re.compile(
|
|
40
|
+
r"{%\s*"
|
|
41
|
+
+ _component_tag
|
|
42
|
+
+ r"\s*"
|
|
43
|
+
+ _component_path
|
|
44
|
+
+ rf"({_component_offline_kwarg}|{_component_generic_kwarg})*?"
|
|
45
|
+
+ r"\s*%}"
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
async def render_view(
|
|
50
|
+
view: Callable | View,
|
|
51
|
+
request: HttpRequest,
|
|
52
|
+
args: Sequence,
|
|
53
|
+
kwargs: dict,
|
|
54
|
+
) -> HttpResponse:
|
|
55
|
+
"""Ingests a Django view (class or function) and returns an HTTP response object."""
|
|
56
|
+
# Convert class-based view to function-based view
|
|
57
|
+
if getattr(view, "as_view", None):
|
|
58
|
+
view = view.as_view() # type: ignore[union-attr]
|
|
59
|
+
|
|
60
|
+
# Async function view
|
|
61
|
+
if iscoroutinefunction(view):
|
|
62
|
+
response = await view(request, *args, **kwargs)
|
|
63
|
+
|
|
64
|
+
# Sync function view
|
|
65
|
+
else:
|
|
66
|
+
response = await database_sync_to_async(view)(request, *args, **kwargs)
|
|
67
|
+
|
|
68
|
+
# TemplateView
|
|
69
|
+
if getattr(response, "render", None):
|
|
70
|
+
response = await database_sync_to_async(response.render)()
|
|
71
|
+
|
|
72
|
+
return response
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def register_component(component: ComponentConstructor | str):
|
|
76
|
+
"""Adds a component to the list of known registered components.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
component: The component to register. Can be a component function or dotted path to a component.
|
|
80
|
+
|
|
81
|
+
"""
|
|
82
|
+
from reactpy_django.config import (
|
|
83
|
+
REACTPY_FAILED_COMPONENTS,
|
|
84
|
+
REACTPY_REGISTERED_COMPONENTS,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
dotted_path = (
|
|
88
|
+
component if isinstance(component, str) else generate_obj_name(component)
|
|
89
|
+
)
|
|
90
|
+
try:
|
|
91
|
+
REACTPY_REGISTERED_COMPONENTS[dotted_path] = import_dotted_path(dotted_path)
|
|
92
|
+
except AttributeError as e:
|
|
93
|
+
REACTPY_FAILED_COMPONENTS.add(dotted_path)
|
|
94
|
+
raise ComponentDoesNotExistError(
|
|
95
|
+
f"Error while fetching '{dotted_path}'. {(str(e).capitalize())}."
|
|
96
|
+
) from e
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def register_iframe(view: Callable | View | str):
|
|
100
|
+
"""Registers a view to be used as an iframe component.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
view: The view to register. Can be a function or class based view, or a dotted path to a view.
|
|
104
|
+
"""
|
|
105
|
+
from reactpy_django.config import REACTPY_REGISTERED_IFRAME_VIEWS
|
|
106
|
+
|
|
107
|
+
if hasattr(view, "view_class"):
|
|
108
|
+
view = view.view_class
|
|
109
|
+
dotted_path = view if isinstance(view, str) else generate_obj_name(view)
|
|
110
|
+
try:
|
|
111
|
+
REACTPY_REGISTERED_IFRAME_VIEWS[dotted_path] = import_dotted_path(dotted_path)
|
|
112
|
+
except AttributeError as e:
|
|
113
|
+
raise ViewDoesNotExistError(
|
|
114
|
+
f"Error while fetching '{dotted_path}'. {(str(e).capitalize())}."
|
|
115
|
+
) from e
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def import_dotted_path(dotted_path: str) -> Callable:
|
|
119
|
+
"""Imports a dotted path and returns the callable."""
|
|
120
|
+
module_name, component_name = dotted_path.rsplit(".", 1)
|
|
121
|
+
|
|
122
|
+
try:
|
|
123
|
+
module = import_module(module_name)
|
|
124
|
+
except ImportError as error:
|
|
125
|
+
raise RuntimeError(
|
|
126
|
+
f"Failed to import {module_name!r} while loading {component_name!r}"
|
|
127
|
+
) from error
|
|
128
|
+
|
|
129
|
+
return getattr(module, component_name)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class RootComponentFinder:
|
|
133
|
+
"""Searches Django templates to find and register all root components.
|
|
134
|
+
This should only be `run` once on startup to maintain synchronization during mulitprocessing.
|
|
135
|
+
"""
|
|
136
|
+
|
|
137
|
+
def run(self):
|
|
138
|
+
"""Registers all ReactPy components found within Django templates."""
|
|
139
|
+
# Get all template folder paths
|
|
140
|
+
paths = self.get_paths()
|
|
141
|
+
# Get all HTML template files
|
|
142
|
+
templates = self.get_templates(paths)
|
|
143
|
+
# Get all components
|
|
144
|
+
components = self.get_components(templates)
|
|
145
|
+
# Register all components
|
|
146
|
+
self.register_components(components)
|
|
147
|
+
|
|
148
|
+
def get_loaders(self):
|
|
149
|
+
"""Obtains currently configured template loaders."""
|
|
150
|
+
template_source_loaders = []
|
|
151
|
+
for e in engines.all():
|
|
152
|
+
if hasattr(e, "engine"):
|
|
153
|
+
template_source_loaders.extend(
|
|
154
|
+
e.engine.get_template_loaders(e.engine.loaders)
|
|
155
|
+
)
|
|
156
|
+
loaders = []
|
|
157
|
+
for loader in template_source_loaders:
|
|
158
|
+
if hasattr(loader, "loaders"):
|
|
159
|
+
loaders.extend(loader.loaders)
|
|
160
|
+
else:
|
|
161
|
+
loaders.append(loader)
|
|
162
|
+
return loaders
|
|
163
|
+
|
|
164
|
+
def get_paths(self) -> set[str]:
|
|
165
|
+
"""Obtains a set of all template directories."""
|
|
166
|
+
paths: set[str] = set()
|
|
167
|
+
for loader in self.get_loaders():
|
|
168
|
+
with contextlib.suppress(ImportError, AttributeError, TypeError):
|
|
169
|
+
module = import_module(loader.__module__)
|
|
170
|
+
get_template_sources = getattr(module, "get_template_sources", None)
|
|
171
|
+
if get_template_sources is None:
|
|
172
|
+
get_template_sources = loader.get_template_sources
|
|
173
|
+
paths.update(smart_str(origin) for origin in get_template_sources(""))
|
|
174
|
+
return paths
|
|
175
|
+
|
|
176
|
+
def get_templates(self, paths: set[str]) -> set[str]:
|
|
177
|
+
"""Obtains a set of all HTML template paths."""
|
|
178
|
+
extensions = [".html"]
|
|
179
|
+
templates: set[str] = set()
|
|
180
|
+
for path in paths:
|
|
181
|
+
for root, _, files in os.walk(path, followlinks=False):
|
|
182
|
+
templates.update(
|
|
183
|
+
os.path.join(root, name)
|
|
184
|
+
for name in files
|
|
185
|
+
if not name.startswith(".")
|
|
186
|
+
and any(fnmatch(name, f"*{glob}") for glob in extensions)
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
return templates
|
|
190
|
+
|
|
191
|
+
def get_components(self, templates: set[str]) -> set[str]:
|
|
192
|
+
"""Obtains a set of all ReactPy components by parsing HTML templates."""
|
|
193
|
+
components: set[str] = set()
|
|
194
|
+
for template in templates:
|
|
195
|
+
with contextlib.suppress(Exception):
|
|
196
|
+
with open(template, "r", encoding="utf-8") as template_file:
|
|
197
|
+
clean_template = COMMENT_REGEX.sub("", template_file.read())
|
|
198
|
+
regex_iterable = COMPONENT_REGEX.finditer(clean_template)
|
|
199
|
+
new_components: list[str] = []
|
|
200
|
+
for match in regex_iterable:
|
|
201
|
+
new_components.append(
|
|
202
|
+
match.group("path").replace('"', "").replace("'", "")
|
|
203
|
+
)
|
|
204
|
+
offline_path = match.group("offline_path")
|
|
205
|
+
if offline_path:
|
|
206
|
+
new_components.append(
|
|
207
|
+
offline_path.replace('"', "").replace("'", "")
|
|
208
|
+
)
|
|
209
|
+
components.update(new_components)
|
|
210
|
+
if not components:
|
|
211
|
+
_logger.warning(
|
|
212
|
+
"\033[93m"
|
|
213
|
+
"ReactPy did not find any components! "
|
|
214
|
+
"You are either not using any ReactPy components, "
|
|
215
|
+
"using the template tag incorrectly, "
|
|
216
|
+
"or your HTML templates are not registered with Django."
|
|
217
|
+
"\033[0m"
|
|
218
|
+
)
|
|
219
|
+
return components
|
|
220
|
+
|
|
221
|
+
def register_components(self, components: set[str]) -> None:
|
|
222
|
+
"""Registers all ReactPy components in an iterable."""
|
|
223
|
+
if components:
|
|
224
|
+
_logger.debug("Auto-detected ReactPy root components:")
|
|
225
|
+
for component in components:
|
|
226
|
+
try:
|
|
227
|
+
_logger.debug("\t+ %s", component)
|
|
228
|
+
register_component(component)
|
|
229
|
+
except Exception:
|
|
230
|
+
_logger.exception(
|
|
231
|
+
"\033[91m"
|
|
232
|
+
"ReactPy failed to register component '%s'!\n"
|
|
233
|
+
"This component path may not be valid, "
|
|
234
|
+
"or an exception may have occurred while importing.\n"
|
|
235
|
+
"See the traceback below for more information."
|
|
236
|
+
"\033[0m",
|
|
237
|
+
component,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def generate_obj_name(obj: Any) -> str:
|
|
242
|
+
"""Makes a best effort to create a name for an object.
|
|
243
|
+
Useful for JSON serialization of Python objects."""
|
|
244
|
+
|
|
245
|
+
# First attempt: Dunder methods
|
|
246
|
+
if hasattr(obj, "__module__"):
|
|
247
|
+
if hasattr(obj, "__name__"):
|
|
248
|
+
return f"{obj.__module__}.{obj.__name__}"
|
|
249
|
+
if hasattr(obj, "__class__") and hasattr(obj.__class__, "__name__"):
|
|
250
|
+
return f"{obj.__module__}.{obj.__class__.__name__}"
|
|
251
|
+
|
|
252
|
+
# Second attempt: String representation
|
|
253
|
+
with contextlib.suppress(Exception):
|
|
254
|
+
return str(obj)
|
|
255
|
+
|
|
256
|
+
# Fallback: Empty string
|
|
257
|
+
return ""
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def django_query_postprocessor(
|
|
261
|
+
data: QuerySet | Model, many_to_many: bool = True, many_to_one: bool = True
|
|
262
|
+
) -> QuerySet | Model:
|
|
263
|
+
"""Recursively fetch all fields within a `Model` or `QuerySet` to ensure they are not performed lazily.
|
|
264
|
+
|
|
265
|
+
Behaviors can be modified through `QueryOptions` within your `use_query` hook.
|
|
266
|
+
|
|
267
|
+
Args:
|
|
268
|
+
data: The `Model` or `QuerySet` to recursively fetch fields from.
|
|
269
|
+
|
|
270
|
+
Keyword Args:
|
|
271
|
+
many_to_many: Whether or not to recursively fetch `ManyToManyField` relationships.
|
|
272
|
+
many_to_one: Whether or not to recursively fetch `ForeignKey` relationships.
|
|
273
|
+
|
|
274
|
+
Returns:
|
|
275
|
+
The `Model` or `QuerySet` with all fields fetched.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
# `QuerySet`, which is an iterable of `Model`/`QuerySet` instances
|
|
279
|
+
# https://github.com/typeddjango/django-stubs/issues/704
|
|
280
|
+
if isinstance(data, QuerySet): # type: ignore[misc]
|
|
281
|
+
for model in data:
|
|
282
|
+
django_query_postprocessor(
|
|
283
|
+
model,
|
|
284
|
+
many_to_many=many_to_many,
|
|
285
|
+
many_to_one=many_to_one,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
# `Model` instances
|
|
289
|
+
elif isinstance(data, Model):
|
|
290
|
+
prefetch_fields: list[str] = []
|
|
291
|
+
for field in data._meta.get_fields():
|
|
292
|
+
# Force the query to execute
|
|
293
|
+
getattr(data, field.name, None)
|
|
294
|
+
|
|
295
|
+
if many_to_one and type(field) == ManyToOneRel: # noqa: E721
|
|
296
|
+
prefetch_fields.append(field.related_name or f"{field.name}_set")
|
|
297
|
+
|
|
298
|
+
elif many_to_many and isinstance(field, ManyToManyField):
|
|
299
|
+
prefetch_fields.append(field.name)
|
|
300
|
+
|
|
301
|
+
if prefetch_fields:
|
|
302
|
+
prefetch_related_objects([data], *prefetch_fields)
|
|
303
|
+
for field_str in prefetch_fields:
|
|
304
|
+
django_query_postprocessor(
|
|
305
|
+
getattr(data, field_str).get_queryset(),
|
|
306
|
+
many_to_many=many_to_many,
|
|
307
|
+
many_to_one=many_to_one,
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
# Unrecognized type
|
|
311
|
+
else:
|
|
312
|
+
raise TypeError(
|
|
313
|
+
f"Django query postprocessor expected a Model or QuerySet, got {data!r}.\n"
|
|
314
|
+
"One of the following may have occurred:\n"
|
|
315
|
+
" - You are using a non-Django ORM.\n"
|
|
316
|
+
" - You are attempting to use `use_query` to fetch non-ORM data.\n\n"
|
|
317
|
+
"If these situations seem correct, you may want to consider disabling the postprocessor via `QueryOptions`."
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
return data
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def validate_component_args(func, *args, **kwargs):
|
|
324
|
+
"""
|
|
325
|
+
Validate whether a set of args/kwargs would work on the given component.
|
|
326
|
+
|
|
327
|
+
Raises `ComponentParamError` if the args/kwargs are invalid.
|
|
328
|
+
"""
|
|
329
|
+
signature = inspect.signature(func)
|
|
330
|
+
|
|
331
|
+
try:
|
|
332
|
+
signature.bind(*args, **kwargs)
|
|
333
|
+
except TypeError as e:
|
|
334
|
+
name = generate_obj_name(func)
|
|
335
|
+
raise ComponentParamError(
|
|
336
|
+
f"Invalid args for '{name}'. {str(e).capitalize()}."
|
|
337
|
+
) from e
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def create_cache_key(*args):
|
|
341
|
+
"""Creates a cache key string that starts with `reactpy_django` contains
|
|
342
|
+
all *args separated by `:`."""
|
|
343
|
+
|
|
344
|
+
if not args:
|
|
345
|
+
raise ValueError("At least one argument is required to create a cache key.")
|
|
346
|
+
|
|
347
|
+
return f"reactpy_django:{':'.join(str(arg) for arg in args)}"
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
class SyncLayout(Layout):
|
|
351
|
+
"""Sync adapter for ReactPy's `Layout`. Allows it to be used in Django template tags.
|
|
352
|
+
This can be removed when Django supports async template tags.
|
|
353
|
+
"""
|
|
354
|
+
|
|
355
|
+
def __enter__(self):
|
|
356
|
+
async_to_sync(self.__aenter__)()
|
|
357
|
+
return self
|
|
358
|
+
|
|
359
|
+
def __exit__(self, *_):
|
|
360
|
+
async_to_sync(self.__aexit__)(*_)
|
|
361
|
+
|
|
362
|
+
def render(self):
|
|
363
|
+
return async_to_sync(super().render)()
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def get_pk(model):
|
|
367
|
+
"""Returns the value of the primary key for a Django model."""
|
|
368
|
+
return getattr(model, model._meta.pk.name)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def strtobool(val):
|
|
372
|
+
"""Convert a string representation of truth to true (1) or false (0).
|
|
373
|
+
|
|
374
|
+
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
|
|
375
|
+
are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
|
|
376
|
+
'val' is anything else.
|
|
377
|
+
"""
|
|
378
|
+
val = val.lower()
|
|
379
|
+
if val in ("y", "yes", "t", "true", "on", "1"):
|
|
380
|
+
return 1
|
|
381
|
+
elif val in ("n", "no", "f", "false", "off", "0"):
|
|
382
|
+
return 0
|
|
383
|
+
else:
|
|
384
|
+
raise ValueError("invalid truth value %r" % (val,))
|
|
File without changes
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""Anything used to construct a websocket endpoint"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import logging
|
|
8
|
+
import traceback
|
|
9
|
+
from concurrent.futures import Future
|
|
10
|
+
from datetime import timedelta
|
|
11
|
+
from threading import Thread
|
|
12
|
+
from typing import TYPE_CHECKING, Any, MutableMapping, Sequence
|
|
13
|
+
from urllib.parse import parse_qs
|
|
14
|
+
|
|
15
|
+
import dill as pickle
|
|
16
|
+
import orjson
|
|
17
|
+
from channels.auth import login
|
|
18
|
+
from channels.db import database_sync_to_async
|
|
19
|
+
from channels.generic.websocket import AsyncJsonWebsocketConsumer
|
|
20
|
+
from django.utils import timezone
|
|
21
|
+
from reactpy.backend.hooks import ConnectionContext
|
|
22
|
+
from reactpy.backend.types import Connection, Location
|
|
23
|
+
from reactpy.core.layout import Layout
|
|
24
|
+
from reactpy.core.serve import serve_layout
|
|
25
|
+
|
|
26
|
+
from reactpy_django.clean import clean
|
|
27
|
+
from reactpy_django.types import ComponentParams
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from django.contrib.auth.models import AbstractUser
|
|
31
|
+
|
|
32
|
+
_logger = logging.getLogger(__name__)
|
|
33
|
+
BACKHAUL_LOOP = asyncio.new_event_loop()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def start_backhaul_loop():
|
|
37
|
+
"""Starts the asyncio event loop that will perform component rendering tasks."""
|
|
38
|
+
asyncio.set_event_loop(BACKHAUL_LOOP)
|
|
39
|
+
BACKHAUL_LOOP.run_forever()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
BACKHAUL_THREAD = Thread(
|
|
43
|
+
target=start_backhaul_loop, daemon=True, name="ReactPyBackhaul"
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class ReactpyAsyncWebsocketConsumer(AsyncJsonWebsocketConsumer):
|
|
48
|
+
"""Communicates with the browser to perform actions on-demand."""
|
|
49
|
+
|
|
50
|
+
async def connect(self) -> None:
|
|
51
|
+
"""The browser has connected."""
|
|
52
|
+
from reactpy_django import models
|
|
53
|
+
from reactpy_django.config import (
|
|
54
|
+
REACTPY_AUTH_BACKEND,
|
|
55
|
+
REACTPY_AUTO_RELOGIN,
|
|
56
|
+
REACTPY_BACKHAUL_THREAD,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
await super().connect()
|
|
60
|
+
|
|
61
|
+
# Automatically re-login the user, if needed
|
|
62
|
+
user: AbstractUser | None = self.scope.get("user")
|
|
63
|
+
if REACTPY_AUTO_RELOGIN and user and user.is_authenticated and user.is_active:
|
|
64
|
+
try:
|
|
65
|
+
await login(self.scope, user, backend=REACTPY_AUTH_BACKEND)
|
|
66
|
+
except Exception:
|
|
67
|
+
await asyncio.to_thread(
|
|
68
|
+
_logger.error,
|
|
69
|
+
"ReactPy websocket authentication has failed!\n"
|
|
70
|
+
f"{traceback.format_exc()}",
|
|
71
|
+
)
|
|
72
|
+
try:
|
|
73
|
+
await database_sync_to_async(self.scope["session"].save)()
|
|
74
|
+
except Exception:
|
|
75
|
+
await asyncio.to_thread(
|
|
76
|
+
_logger.error,
|
|
77
|
+
"ReactPy has failed to save scope['session']!\n"
|
|
78
|
+
f"{traceback.format_exc()}",
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# Start the component dispatcher
|
|
82
|
+
self.dispatcher: Future | asyncio.Task
|
|
83
|
+
self.threaded = REACTPY_BACKHAUL_THREAD
|
|
84
|
+
self.component_session: models.ComponentSession | None = None
|
|
85
|
+
if self.threaded:
|
|
86
|
+
if not BACKHAUL_THREAD.is_alive():
|
|
87
|
+
await asyncio.to_thread(
|
|
88
|
+
_logger.debug, "Starting ReactPy backhaul thread."
|
|
89
|
+
)
|
|
90
|
+
BACKHAUL_THREAD.start()
|
|
91
|
+
self.dispatcher = asyncio.run_coroutine_threadsafe(
|
|
92
|
+
self.run_dispatcher(), BACKHAUL_LOOP
|
|
93
|
+
)
|
|
94
|
+
else:
|
|
95
|
+
self.dispatcher = asyncio.create_task(self.run_dispatcher())
|
|
96
|
+
|
|
97
|
+
async def disconnect(self, code: int) -> None:
|
|
98
|
+
"""The browser has disconnected."""
|
|
99
|
+
from reactpy_django.config import REACTPY_CLEAN_INTERVAL
|
|
100
|
+
|
|
101
|
+
self.dispatcher.cancel()
|
|
102
|
+
|
|
103
|
+
# Update the component's last_accessed timestamp
|
|
104
|
+
if self.component_session:
|
|
105
|
+
try:
|
|
106
|
+
await self.component_session.asave()
|
|
107
|
+
except Exception:
|
|
108
|
+
await asyncio.to_thread(
|
|
109
|
+
_logger.error,
|
|
110
|
+
"ReactPy has failed to save component session!\n"
|
|
111
|
+
f"{traceback.format_exc()}",
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Queue a cleanup, if needed
|
|
115
|
+
if REACTPY_CLEAN_INTERVAL is not None:
|
|
116
|
+
try:
|
|
117
|
+
await database_sync_to_async(clean)()
|
|
118
|
+
except Exception:
|
|
119
|
+
await asyncio.to_thread(
|
|
120
|
+
_logger.error,
|
|
121
|
+
"ReactPy cleaning failed!\n" f"{traceback.format_exc()}",
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
await super().disconnect(code)
|
|
125
|
+
|
|
126
|
+
async def receive_json(self, content: Any, **_) -> None:
|
|
127
|
+
"""Receive a message from the browser. Typically, messages are event signals."""
|
|
128
|
+
if self.threaded:
|
|
129
|
+
asyncio.run_coroutine_threadsafe(
|
|
130
|
+
self.recv_queue.put(content), BACKHAUL_LOOP
|
|
131
|
+
)
|
|
132
|
+
else:
|
|
133
|
+
await self.recv_queue.put(content)
|
|
134
|
+
|
|
135
|
+
@classmethod
|
|
136
|
+
async def decode_json(cls, text_data):
|
|
137
|
+
return orjson.loads(text_data)
|
|
138
|
+
|
|
139
|
+
@classmethod
|
|
140
|
+
async def encode_json(cls, content):
|
|
141
|
+
return orjson.dumps(content).decode()
|
|
142
|
+
|
|
143
|
+
async def run_dispatcher(self):
|
|
144
|
+
"""Runs the main loop that performs component rendering tasks."""
|
|
145
|
+
from reactpy_django import models
|
|
146
|
+
from reactpy_django.config import (
|
|
147
|
+
REACTPY_REGISTERED_COMPONENTS,
|
|
148
|
+
REACTPY_SESSION_MAX_AGE,
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
scope = self.scope
|
|
152
|
+
self.dotted_path = dotted_path = scope["url_route"]["kwargs"]["dotted_path"]
|
|
153
|
+
uuid = scope["url_route"]["kwargs"].get("uuid")
|
|
154
|
+
has_args = scope["url_route"]["kwargs"].get("has_args")
|
|
155
|
+
scope["reactpy"] = {"id": str(uuid)}
|
|
156
|
+
query_string = parse_qs(scope["query_string"].decode(), strict_parsing=True)
|
|
157
|
+
http_pathname = query_string.get("http_pathname", [""])[0]
|
|
158
|
+
http_search = query_string.get("http_search", [""])[0]
|
|
159
|
+
self.recv_queue: asyncio.Queue = asyncio.Queue()
|
|
160
|
+
connection = Connection( # For `use_connection`
|
|
161
|
+
scope=scope,
|
|
162
|
+
location=Location(pathname=http_pathname, search=http_search),
|
|
163
|
+
carrier=self,
|
|
164
|
+
)
|
|
165
|
+
now = timezone.now()
|
|
166
|
+
component_session_args: Sequence[Any] = ()
|
|
167
|
+
component_session_kwargs: MutableMapping[str, Any] = {}
|
|
168
|
+
|
|
169
|
+
# Verify the component has already been registered
|
|
170
|
+
try:
|
|
171
|
+
root_component_constructor = REACTPY_REGISTERED_COMPONENTS[dotted_path]
|
|
172
|
+
except KeyError:
|
|
173
|
+
await asyncio.to_thread(
|
|
174
|
+
_logger.warning,
|
|
175
|
+
f"Attempt to access invalid ReactPy component: {dotted_path!r}",
|
|
176
|
+
)
|
|
177
|
+
return
|
|
178
|
+
|
|
179
|
+
# Construct the component. This may require fetching the component's args/kwargs from the database.
|
|
180
|
+
try:
|
|
181
|
+
if has_args:
|
|
182
|
+
self.component_session = await models.ComponentSession.objects.aget(
|
|
183
|
+
uuid=uuid,
|
|
184
|
+
last_accessed__gt=now - timedelta(seconds=REACTPY_SESSION_MAX_AGE),
|
|
185
|
+
)
|
|
186
|
+
params: ComponentParams = pickle.loads(self.component_session.params)
|
|
187
|
+
component_session_args = params.args
|
|
188
|
+
component_session_kwargs = params.kwargs
|
|
189
|
+
|
|
190
|
+
# Generate the initial component instance
|
|
191
|
+
root_component = root_component_constructor(
|
|
192
|
+
*component_session_args, **component_session_kwargs
|
|
193
|
+
)
|
|
194
|
+
except models.ComponentSession.DoesNotExist:
|
|
195
|
+
await asyncio.to_thread(
|
|
196
|
+
_logger.warning,
|
|
197
|
+
f"Component session for '{dotted_path}:{uuid}' not found. The "
|
|
198
|
+
"session may have already expired beyond REACTPY_SESSION_MAX_AGE. "
|
|
199
|
+
"If you are using a custom `host`, you may have forgotten to provide "
|
|
200
|
+
"args/kwargs.",
|
|
201
|
+
)
|
|
202
|
+
return
|
|
203
|
+
except Exception:
|
|
204
|
+
await asyncio.to_thread(
|
|
205
|
+
_logger.error,
|
|
206
|
+
f"Failed to construct component {root_component_constructor} "
|
|
207
|
+
f"with args='{component_session_args}' kwargs='{component_session_kwargs}'!\n"
|
|
208
|
+
f"{traceback.format_exc()}",
|
|
209
|
+
)
|
|
210
|
+
return
|
|
211
|
+
|
|
212
|
+
# Start the ReactPy component rendering loop
|
|
213
|
+
with contextlib.suppress(Exception):
|
|
214
|
+
await serve_layout(
|
|
215
|
+
Layout(ConnectionContext(root_component, value=connection)),
|
|
216
|
+
self.send_json,
|
|
217
|
+
self.recv_queue.get,
|
|
218
|
+
)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from django.urls import path
|
|
2
|
+
|
|
3
|
+
from reactpy_django.config import REACTPY_URL_PREFIX
|
|
4
|
+
|
|
5
|
+
from .consumer import ReactpyAsyncWebsocketConsumer
|
|
6
|
+
|
|
7
|
+
REACTPY_WEBSOCKET_ROUTE = path(
|
|
8
|
+
f"{REACTPY_URL_PREFIX}/<str:dotted_path>/<uuid:uuid>/<int:has_args>/",
|
|
9
|
+
ReactpyAsyncWebsocketConsumer.as_asgi(),
|
|
10
|
+
)
|
|
11
|
+
"""A URL path for :class:`ReactpyAsyncWebsocketConsumer`.
|
|
12
|
+
|
|
13
|
+
Required since the `reverse()` function does not exist for Django Channels, but we need
|
|
14
|
+
to know the websocket path.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
REACTPY_WEBSOCKET_PATH = REACTPY_WEBSOCKET_ROUTE
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
## The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
#### Copyright (c) Reactive Python and affiliates.
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|