-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdjango_views.py
More file actions
532 lines (410 loc) · 19.4 KB
/
Copy pathdjango_views.py
File metadata and controls
532 lines (410 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
"""Django view adapters for component endpoints."""
import json
import logging
try:
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.http import HttpRequest, JsonResponse
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.views.generic import TemplateView
except ImportError as e:
from . import _require_extra
raise _require_extra("django", "django") from e
from ..core import Component, StateSerializer, registry
from ..core.permissions import AllowAny
logger = logging.getLogger(__name__)
@require_POST
def component_view(request: HttpRequest, name: str) -> JsonResponse:
"""
Django view for component endpoints.
POST /components/{name}/
Body (JSON or form-data):
- event: Event name
- payload: Event data (JSON string)
- state: Serialized state (JSON string)
- params: Component parameters (JSON string)
Returns:
JSON response with html, state, and component_id
"""
try:
# Get component class
component_cls = registry.get(name)
if not component_cls:
return JsonResponse({"error": f"Component '{name}' not found"}, status=404)
# Check component-level permissions
for perm_class in getattr(component_cls, "permission_classes", []) or [AllowAny]:
if not perm_class().has_permission(request, component_cls):
return JsonResponse({"error": "Permission denied"}, status=403)
# Parse request data (supports both JSON and form-encoded)
if request.content_type == "application/json":
try:
data = json.loads(request.body)
except json.JSONDecodeError as e:
return JsonResponse({"error": f"Invalid JSON: {e}"}, status=400)
else:
data = {
"event": request.POST.get("event"),
"payload": request.POST.get("payload", "{}"),
"state": request.POST.get("state"),
"params": request.POST.get("params", "{}"),
}
# Extract parameters
event = data.get("event")
payload_str = data.get("payload", "{}")
state_str = data.get("state")
params_str = data.get("params", "{}")
# Parse JSON strings
try:
payload = json.loads(payload_str) if isinstance(payload_str, str) else payload_str
params = json.loads(params_str) if isinstance(params_str, str) else params_str
except json.JSONDecodeError as e:
return JsonResponse({"error": f"Invalid JSON in payload/params: {e}"}, status=400)
# Deserialize state (verified against the signing key when enabled)
try:
state = StateSerializer.load_untrusted(state_str)
except Exception as e:
return JsonResponse({"error": f"Invalid state: {e}"}, status=400)
# Compute optimistic patch BEFORE dispatch (uses pre-dispatch state).
# Hydrate state so get_optimistic_patch can access current state values.
optimistic_patch: dict | None = None
if event:
probe = component_cls(**params)
if state:
probe.hydrate(state)
else:
probe.mount()
optimistic_patch = probe.get_optimistic_patch(event, payload or {})
# Create and dispatch component
component = component_cls(**params)
result = component.dispatch(event=event, payload=payload, state=state)
# Serialize state for response
result["state"] = StateSerializer.serialize(result["state"])
# Include optimistic patch if the component provided one
if optimistic_patch is not None:
result["optimistic"] = optimistic_patch
return JsonResponse(result)
except Exception:
logger.exception(f"Error processing component '{name}'")
return JsonResponse({"error": "Internal server error"}, status=500)
# CSRF-exempt version for HTMX requests (use with caution)
component_view_no_csrf = csrf_exempt(component_view)
def create_component_url_pattern():
"""
Create URL pattern for component endpoint.
Usage in urls.py:
from component_framework.adapters.django_views import create_component_url_pattern
urlpatterns = [
create_component_url_pattern(),
]
"""
from django.urls import path
return path("components/<str:name>/", component_view, name="component_endpoint")
# ==================== Class-Based Views ====================
class ComponentView(View):
"""
Class-based view for component endpoints.
Usage:
# urls.py
from component_framework.adapters.django_views import ComponentView
urlpatterns = [
path("components/<str:name>/", ComponentView.as_view()),
]
Or with custom configuration:
class MyComponentView(ComponentView):
http_method_names = ['post', 'get'] # Allow GET too
def get_component_params(self, request, **kwargs):
# Custom param extraction
params = super().get_component_params(request, **kwargs)
params['user_id'] = request.user.id
return params
"""
http_method_names = ["post"]
def check_component_permissions(
self, request: HttpRequest, component_cls: type[Component]
) -> JsonResponse | None:
"""
Check component-level permission_classes.
Returns a JsonResponse (403) if any permission class denies access,
or None if all permissions are granted.
"""
for perm_class in getattr(component_cls, "permission_classes", []) or [AllowAny]:
if not perm_class().has_permission(request, component_cls):
return JsonResponse({"error": "Permission denied"}, status=403)
return None
def post(self, request: HttpRequest, name: str, **kwargs) -> JsonResponse:
"""Handle POST request for component."""
try:
# Get component class
component_cls = self.get_component_class(name)
if not component_cls:
return self.component_not_found(name)
# Check component-level permissions
perm_response = self.check_component_permissions(request, component_cls)
if perm_response is not None:
return perm_response
# Parse request data
data = self.parse_request_data(request)
# Extract component parameters
event = data.get("event")
payload = self.parse_payload(data.get("payload", "{}"))
state = self.parse_state(data.get("state"))
params = self.parse_params(data.get("params", "{}"))
# Add custom params
params.update(self.get_component_params(request, **kwargs))
# Compute optimistic patch BEFORE dispatch (uses pre-dispatch state).
# A separate probe instance is used so the real dispatch starts clean.
optimistic_patch: dict | None = None
if event:
probe = self.create_component(component_cls, params)
if state:
probe.hydrate(state)
else:
probe.mount()
optimistic_patch = probe.get_optimistic_patch(event, payload)
# Create and dispatch component
component = self.create_component(component_cls, params)
result = self.dispatch_component(component, event, payload, state)
# Post-process result
result = self.post_process_result(result, component)
# Attach optimistic patch if the component provided one
if optimistic_patch is not None:
result["optimistic"] = optimistic_patch
return self.render_response(result)
except Exception as e:
return self.handle_error(e, name)
def get_component_class(self, name: str) -> type[Component] | None:
"""Get component class from registry."""
return registry.get(name)
def parse_request_data(self, request: HttpRequest) -> dict:
"""Parse request data (JSON or form-encoded)."""
if request.content_type == "application/json":
try:
return json.loads(request.body)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON: {e}")
else:
return {
"event": request.POST.get("event"),
"payload": request.POST.get("payload", "{}"),
"state": request.POST.get("state"),
"params": request.POST.get("params", "{}"),
}
def parse_payload(self, payload_str: str | dict) -> dict:
"""Parse payload JSON string."""
if isinstance(payload_str, dict):
return payload_str
try:
return json.loads(payload_str)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid payload JSON: {e}")
def parse_state(self, state_raw: str | dict | None) -> dict | None:
"""Parse client-supplied state (signed token, JSON string, or dict).
Routes through :meth:`StateSerializer.load_untrusted` so raw dicts
cannot bypass signature verification when signing is enabled.
"""
try:
return StateSerializer.load_untrusted(state_raw)
except Exception as e:
raise ValueError(f"Invalid state: {e}")
def parse_params(self, params_str: str | dict) -> dict:
"""Parse params JSON string."""
if isinstance(params_str, dict):
return params_str
try:
return json.loads(params_str)
except json.JSONDecodeError as e:
raise ValueError(f"Invalid params JSON: {e}")
def get_component_params(self, request: HttpRequest, **kwargs) -> dict:
"""
Get additional component parameters.
Override to inject custom parameters (user, session data, etc.)
"""
return {}
def create_component(self, component_cls: type[Component], params: dict) -> Component:
"""Create component instance."""
return component_cls(**params)
def dispatch_component(
self, component: Component, event: str | None, payload: dict, state: dict | None
) -> dict:
"""Dispatch component with event."""
return component.dispatch(event=event, payload=payload, state=state)
def post_process_result(self, result: dict, component: Component) -> dict:
"""Post-process component result. Override to add custom data."""
result["state"] = StateSerializer.serialize(result["state"])
return result
def render_response(self, result: dict) -> JsonResponse:
"""Render JSON response."""
return JsonResponse(result)
def component_not_found(self, name: str) -> JsonResponse:
"""Handle component not found."""
return JsonResponse({"error": f"Component '{name}' not found"}, status=404)
def handle_error(self, error: Exception, name: str) -> JsonResponse:
"""Handle errors.
Client input errors (bad JSON, tampered/corrupt state) map to 400;
everything else maps to 500.
"""
if isinstance(error, ValueError):
logger.warning("Bad request for component '%s': %s", name, error)
return JsonResponse({"error": str(error)}, status=400)
logger.exception(f"Error processing component '{name}'")
return JsonResponse({"error": "Internal server error"}, status=500)
class AuthenticatedComponentView(LoginRequiredMixin, ComponentView):
"""
Component view that requires authentication.
Returns a JSON 401 response (not a redirect) for unauthenticated requests,
making it safe for HTMX/fetch consumers.
Usage:
urlpatterns = [
path("components/<str:name>/", AuthenticatedComponentView.as_view()),
]
"""
def handle_no_permission(self) -> JsonResponse:
"""Return JSON 401 instead of redirecting to login."""
return JsonResponse({"error": "Authentication required"}, status=401)
def get_component_params(self, request: HttpRequest, **kwargs) -> dict:
"""Add user to component params."""
params = super().get_component_params(request, **kwargs)
params["user"] = request.user # type: ignore[unresolved-attribute] # added by AuthenticationMiddleware
params["user_id"] = request.user.id # type: ignore[unresolved-attribute] # added by AuthenticationMiddleware
return params
class PermissionComponentView(PermissionRequiredMixin, ComponentView):
"""
Component view with permission checking.
Returns a JSON 403 response (not a redirect) when permission is denied,
making it safe for HTMX/fetch consumers.
Usage:
class MyComponentView(PermissionComponentView):
permission_required = 'app.change_model'
# Or dynamic permissions:
class MyComponentView(PermissionComponentView):
def get_permission_required(self):
# Check component-specific permissions
component_name = self.kwargs.get('name')
return f'app.use_{component_name}'
"""
def handle_no_permission(self) -> JsonResponse:
"""Return JSON 403 instead of redirecting."""
return JsonResponse({"error": "Permission denied"}, status=403)
@method_decorator(csrf_exempt, name="dispatch")
class CSRFExemptComponentView(ComponentView):
"""
Component view with CSRF exemption.
Use with caution! Only for HTMX/AJAX requests with alternative CSRF protection.
Usage:
urlpatterns = [
path("api/components/<str:name>/", CSRFExemptComponentView.as_view()),
]
"""
pass
class SingleComponentView(ComponentView):
"""
View for a single, specific component.
Usage:
class CounterView(SingleComponentView):
component_name = "counter"
urlpatterns = [
path("counter/", CounterView.as_view()),
]
"""
component_name: str | None = None
def post(self, request: HttpRequest, **kwargs) -> JsonResponse: # type: ignore[override]
"""Override to use fixed component name."""
if not self.component_name:
raise ValueError("component_name must be set")
return super().post(request, self.component_name, **kwargs)
class ComponentPageView(TemplateView):
"""
Template view that renders a page with components.
Usage:
class MyPageView(ComponentPageView):
template_name = "my_page.html"
components = {
"counter": {"initial": 5},
"form": {"user_id": 123},
}
def get_component_params(self, component_name):
# Override to add dynamic params
params = super().get_component_params(component_name)
if component_name == "form":
params["user_id"] = self.request.user.id
return params
"""
components: dict[str, dict] = {}
def get_context_data(self, **kwargs):
"""Add component rendering to context."""
context = super().get_context_data(**kwargs)
context["components"] = {}
for component_name, params in self.get_components().items():
component_cls = registry.get(component_name)
if component_cls:
# Add custom params
params = self.get_component_params(component_name, params)
# Render component
component = component_cls(**params)
result = component.dispatch()
context["components"][component_name] = result
return context
def get_components(self) -> dict[str, dict]:
"""Get components to render. Override for dynamic components."""
return self.components
def get_component_params(self, component_name: str, params: dict) -> dict:
"""Get parameters for a specific component. Override to add custom params."""
return params.copy()
# ==================== Mixins ====================
class CacheMixin:
"""
Mixin to add caching to component responses via Django's cache framework.
Caches the JSON result of component dispatches (mount/hydrate only). On
subsequent requests with the same component name, params, and state, the
cached result is returned directly without re-dispatching the component.
Cache bypass rules:
- **Event requests** (requests that carry an ``event`` field) are never
served from or written to the cache. Events mutate component state, so
caching them would cause stale state to be returned on the next request.
- **Non-200 responses** are not stored in the cache. Errors, 404s, and
permission denials must always go through the full request cycle.
Attributes:
cache_timeout: Cache TTL in seconds. Defaults to 60.
Customising the cache key:
Override ``get_cache_key`` to produce application-specific keys::
class MyComponentView(CacheMixin, ComponentView):
cache_timeout = 300 # 5 minutes
def get_cache_key(self, name, params, state):
return f"component:{name}:{params.get('id')}"
MRO note:
Always place ``CacheMixin`` *before* ``ComponentView`` in the class
bases so that this ``post`` override runs first::
class CachedView(CacheMixin, ComponentView):
pass
"""
cache_timeout: int = 60
def get_cache_key(self, name: str, params: dict, state: dict | None) -> str:
"""Generate cache key. Override for custom keys."""
import hashlib
params_json = json.dumps(params, sort_keys=True)
state_json = json.dumps(state or {}, sort_keys=True)
key_data = f"{name}:{params_json}:{state_json}"
return f"component:{hashlib.md5(key_data.encode()).hexdigest()}"
def post(self, request: HttpRequest, name: str, **kwargs) -> JsonResponse:
"""Check cache before processing. Event requests bypass the cache entirely."""
from django.core.cache import cache
# Parse request data — methods provided by ComponentView via MRO
data = self.parse_request_data(request) # type: ignore[unresolved-attribute] # cooperative mixin
# Event requests mutate state and must never be served from or stored
# in the cache. Skip all cache logic and go straight to the parent view.
if data.get("event"):
return super().post(request, name, **kwargs) # type: ignore[unresolved-attribute] # cooperative mixin
params = self.parse_params(data.get("params", "{}")) # type: ignore[unresolved-attribute] # cooperative mixin
state = self.parse_state(data.get("state")) # type: ignore[unresolved-attribute] # cooperative mixin
cache_key = self.get_cache_key(name, params, state)
cached_result = cache.get(cache_key)
if cached_result is not None:
return JsonResponse(cached_result)
# Process normally
response = super().post(request, name, **kwargs) # type: ignore[unresolved-attribute] # cooperative mixin
# Only cache successful responses
if response.status_code == 200:
cache.set(cache_key, json.loads(response.content), self.cache_timeout)
return response