django-components 0.129__tar.gz → 0.130__tar.gz

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.
Files changed (62) hide show
  1. {django_components-0.129/src/django_components.egg-info → django_components-0.130}/PKG-INFO +1 -1
  2. {django_components-0.129 → django_components-0.130}/pyproject.toml +1 -1
  3. {django_components-0.129 → django_components-0.130}/src/django_components/component.py +117 -5
  4. {django_components-0.129 → django_components-0.130}/src/django_components/util/context.py +44 -2
  5. {django_components-0.129 → django_components-0.130/src/django_components.egg-info}/PKG-INFO +1 -1
  6. {django_components-0.129 → django_components-0.130}/LICENSE +0 -0
  7. {django_components-0.129 → django_components-0.130}/MANIFEST.in +0 -0
  8. {django_components-0.129 → django_components-0.130}/README.md +0 -0
  9. {django_components-0.129 → django_components-0.130}/setup.cfg +0 -0
  10. {django_components-0.129 → django_components-0.130}/src/django_components/__init__.py +0 -0
  11. {django_components-0.129 → django_components-0.130}/src/django_components/app_settings.py +0 -0
  12. {django_components-0.129 → django_components-0.130}/src/django_components/apps.py +0 -0
  13. {django_components-0.129 → django_components-0.130}/src/django_components/attributes.py +0 -0
  14. {django_components-0.129 → django_components-0.130}/src/django_components/autodiscovery.py +0 -0
  15. {django_components-0.129 → django_components-0.130}/src/django_components/cache.py +0 -0
  16. {django_components-0.129 → django_components-0.130}/src/django_components/component_media.py +0 -0
  17. {django_components-0.129 → django_components-0.130}/src/django_components/component_registry.py +0 -0
  18. {django_components-0.129 → django_components-0.130}/src/django_components/components/__init__.py +0 -0
  19. {django_components-0.129 → django_components-0.130}/src/django_components/components/dynamic.py +0 -0
  20. {django_components-0.129 → django_components-0.130}/src/django_components/context.py +0 -0
  21. {django_components-0.129 → django_components-0.130}/src/django_components/dependencies.py +0 -0
  22. {django_components-0.129 → django_components-0.130}/src/django_components/expression.py +0 -0
  23. {django_components-0.129 → django_components-0.130}/src/django_components/finders.py +0 -0
  24. {django_components-0.129 → django_components-0.130}/src/django_components/library.py +0 -0
  25. {django_components-0.129 → django_components-0.130}/src/django_components/management/__init__.py +0 -0
  26. {django_components-0.129 → django_components-0.130}/src/django_components/management/commands/__init__.py +0 -0
  27. {django_components-0.129 → django_components-0.130}/src/django_components/management/commands/startcomponent.py +0 -0
  28. {django_components-0.129 → django_components-0.130}/src/django_components/management/commands/upgradecomponent.py +0 -0
  29. {django_components-0.129 → django_components-0.130}/src/django_components/middleware.py +0 -0
  30. {django_components-0.129 → django_components-0.130}/src/django_components/node.py +0 -0
  31. {django_components-0.129 → django_components-0.130}/src/django_components/perfutil/__init__.py +0 -0
  32. {django_components-0.129 → django_components-0.130}/src/django_components/perfutil/component.py +0 -0
  33. {django_components-0.129 → django_components-0.130}/src/django_components/perfutil/provide.py +0 -0
  34. {django_components-0.129 → django_components-0.130}/src/django_components/provide.py +0 -0
  35. {django_components-0.129 → django_components-0.130}/src/django_components/py.typed +0 -0
  36. {django_components-0.129 → django_components-0.130}/src/django_components/slots.py +0 -0
  37. {django_components-0.129 → django_components-0.130}/src/django_components/static/django_components/django_components.min.js +0 -0
  38. {django_components-0.129 → django_components-0.130}/src/django_components/tag_formatter.py +0 -0
  39. {django_components-0.129 → django_components-0.130}/src/django_components/template.py +0 -0
  40. {django_components-0.129 → django_components-0.130}/src/django_components/template_loader.py +0 -0
  41. {django_components-0.129 → django_components-0.130}/src/django_components/templatetags/__init__.py +0 -0
  42. {django_components-0.129 → django_components-0.130}/src/django_components/templatetags/component_tags.py +0 -0
  43. {django_components-0.129 → django_components-0.130}/src/django_components/types.py +0 -0
  44. {django_components-0.129 → django_components-0.130}/src/django_components/urls.py +0 -0
  45. {django_components-0.129 → django_components-0.130}/src/django_components/util/__init__.py +0 -0
  46. {django_components-0.129 → django_components-0.130}/src/django_components/util/cache.py +0 -0
  47. {django_components-0.129 → django_components-0.130}/src/django_components/util/component_highlight.py +0 -0
  48. {django_components-0.129 → django_components-0.130}/src/django_components/util/django_monkeypatch.py +0 -0
  49. {django_components-0.129 → django_components-0.130}/src/django_components/util/exception.py +0 -0
  50. {django_components-0.129 → django_components-0.130}/src/django_components/util/loader.py +0 -0
  51. {django_components-0.129 → django_components-0.130}/src/django_components/util/logger.py +0 -0
  52. {django_components-0.129 → django_components-0.130}/src/django_components/util/misc.py +0 -0
  53. {django_components-0.129 → django_components-0.130}/src/django_components/util/nanoid.py +0 -0
  54. {django_components-0.129 → django_components-0.130}/src/django_components/util/tag_parser.py +0 -0
  55. {django_components-0.129 → django_components-0.130}/src/django_components/util/template_parser.py +0 -0
  56. {django_components-0.129 → django_components-0.130}/src/django_components/util/template_tag.py +0 -0
  57. {django_components-0.129 → django_components-0.130}/src/django_components/util/types.py +0 -0
  58. {django_components-0.129 → django_components-0.130}/src/django_components/util/validation.py +0 -0
  59. {django_components-0.129 → django_components-0.130}/src/django_components.egg-info/SOURCES.txt +0 -0
  60. {django_components-0.129 → django_components-0.130}/src/django_components.egg-info/dependency_links.txt +0 -0
  61. {django_components-0.129 → django_components-0.130}/src/django_components.egg-info/requires.txt +0 -0
  62. {django_components-0.129 → django_components-0.130}/src/django_components.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: django_components
3
- Version: 0.129
3
+ Version: 0.130
4
4
  Summary: A way to create simple reusable template components in Django.
5
5
  Author-email: Emil Stenström <emil@emilstenstrom.se>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.129"
7
+ version = "0.130"
8
8
  requires-python = ">=3.8, <4.0"
9
9
  description = "A way to create simple reusable template components in Django."
10
10
  keywords = ["django", "components", "css", "js", "html"]
@@ -70,7 +70,7 @@ from django_components.slots import (
70
70
  )
71
71
  from django_components.template import cached_template
72
72
  from django_components.util.component_highlight import apply_component_highlight
73
- from django_components.util.context import snapshot_context
73
+ from django_components.util.context import gen_context_processors_data, snapshot_context
74
74
  from django_components.util.django_monkeypatch import is_template_cls_patched
75
75
  from django_components.util.exception import component_error_message
76
76
  from django_components.util.logger import trace_component_msg
@@ -114,6 +114,7 @@ class MetadataItem(Generic[ArgsType, KwargsType, SlotsType]):
114
114
  render_id: str
115
115
  input: RenderInput[ArgsType, KwargsType, SlotsType]
116
116
  is_filled: Optional[SlotIsFilled]
117
+ request: Optional[HttpRequest]
117
118
 
118
119
 
119
120
  class ViewFn(Protocol):
@@ -233,6 +234,7 @@ class ComponentContext:
233
234
  fills: Dict[SlotName, Slot]
234
235
  outer_context: Optional[Context]
235
236
  registry: ComponentRegistry
237
+ request: Optional[HttpRequest]
236
238
  # When we render a component, the root component, together with all the nested Components,
237
239
  # shares this dictionary for storing callbacks that are called from within `component_post_render`.
238
240
  # This is so that we can pass them all in when the root component is passed to `component_post_render`.
@@ -663,6 +665,8 @@ class Component(
663
665
  """
664
666
  Input holds the data (like arg, kwargs, slots) that were passed to
665
667
  the current execution of the `render` method.
668
+
669
+ Raises `RuntimeError` if accessed outside of rendering execution.
666
670
  """
667
671
  if not len(self._metadata_stack):
668
672
  raise RuntimeError(f"{self.name}: Tried to access Component input while outside of rendering execution")
@@ -678,6 +682,8 @@ class Component(
678
682
 
679
683
  This attribute is available for use only within the template as `{{ component_vars.is_filled.slot_name }}`,
680
684
  and within `on_render_before` and `on_render_after` hooks.
685
+
686
+ Raises `RuntimeError` if accessed outside of rendering execution.
681
687
  """
682
688
  if not len(self._metadata_stack):
683
689
  raise RuntimeError(
@@ -693,6 +699,93 @@ class Component(
693
699
 
694
700
  return ctx.is_filled
695
701
 
702
+ @property
703
+ def request(self) -> Optional[HttpRequest]:
704
+ """
705
+ [HTTPRequest](https://docs.djangoproject.com/en/5.1/ref/request-response/#django.http.HttpRequest)
706
+ object passed to this component.
707
+
708
+ In regular Django templates, you have to use
709
+ [`RequestContext`](https://docs.djangoproject.com/en/5.1/ref/templates/api/#django.template.RequestContext)
710
+ to pass the `HttpRequest` object to the template.
711
+
712
+ But in Components, you can either use `RequestContext`, or pass the `request` object
713
+ explicitly via [`Component.render()`](../api#django_components.Component.render) and
714
+ [`Component.render_to_response()`](../api#django_components.Component.render_to_response).
715
+
716
+ When a component is nested in another, the child component uses parent's `request` object.
717
+
718
+ Raises `RuntimeError` if accessed outside of rendering execution.
719
+
720
+ **Example:**
721
+
722
+ ```py
723
+ class MyComponent(Component):
724
+ def get_context_data(self):
725
+ user_id = self.request.GET['user_id']
726
+ return {
727
+ 'user_id': user_id,
728
+ }
729
+ ```
730
+ """
731
+ if not len(self._metadata_stack):
732
+ raise RuntimeError(
733
+ f"{self.name}: Tried to access Component's `request` attribute " "while outside of rendering execution"
734
+ )
735
+
736
+ ctx = self._metadata_stack[-1]
737
+ return ctx.request
738
+
739
+ @property
740
+ def context_processors_data(self) -> Dict:
741
+ """
742
+ Retrieve data injected by
743
+ [`context_processors`](https://docs.djangoproject.com/en/5.1/ref/templates/api/#configuring-an-engine).
744
+
745
+ This data is also available from within the component's template, without having to
746
+ return this data from
747
+ [`get_context_data()`](../api#django_components.Component.get_context_data).
748
+
749
+ Unlike regular Django templates, the context processors are applied to components either when:
750
+
751
+ - The component is rendered with `RequestContext` (Regular Django behavior)
752
+ - The component is rendered with a regular `Context` (or none), but the `request` kwarg
753
+ of [`Component.render()`](../api#django_components.Component.render) is set.
754
+ - The component is nested in another component that matches one of the two conditions above.
755
+
756
+ See
757
+ [`Component.request`](../api#django_components.Component.request)
758
+ on how the `request`
759
+ ([HTTPRequest](https://docs.djangoproject.com/en/5.1/ref/request-response/#django.http.HttpRequest))
760
+ object is passed to and within the components.
761
+
762
+ Raises `RuntimeError` if accessed outside of rendering execution.
763
+
764
+ **Example:**
765
+
766
+ ```py
767
+ class MyComponent(Component):
768
+ def get_context_data(self):
769
+ user = self.context_processors_data['user']
770
+ return {
771
+ 'is_logged_in': user.is_authenticated,
772
+ }
773
+ ```
774
+ """
775
+ if not len(self._metadata_stack):
776
+ raise RuntimeError(
777
+ f"{self.name}: Tried to access Component's `context_processors_data` attribute "
778
+ "while outside of rendering execution"
779
+ )
780
+
781
+ context = self.input.context
782
+ request = self.request
783
+
784
+ if request is None:
785
+ return {}
786
+ else:
787
+ return gen_context_processors_data(context, request)
788
+
696
789
  # NOTE: We cache the Template instance. When the template is taken from a file
697
790
  # via `get_template_name`, then we leverage Django's template caching with `get_template()`.
698
791
  # Otherwise, we use our own `cached_template()` to cache the template.
@@ -859,8 +952,7 @@ class Component(
859
952
  or to the end of the `<body>` tag. CSS dependencies are inserted into
860
953
  `{% component_css_dependencies %}`, or the end of the `<head>` tag.
861
954
  - `request` - The request object. This is only required when needing to use RequestContext,
862
- e.g. to enable template `context_processors`. Unused if context is already an instance
863
- of `Context`
955
+ e.g. to enable template `context_processors`.
864
956
 
865
957
  Any additional args and kwargs are passed to the `response_class`.
866
958
 
@@ -929,8 +1021,7 @@ class Component(
929
1021
  `{% component_css_dependencies %}`, or the end of the `<head>` tag.
930
1022
  - `render_dependencies` - Set this to `False` if you want to insert the resulting HTML into another component.
931
1023
  - `request` - The request object. This is only required when needing to use RequestContext,
932
- e.g. to enable template `context_processors`. Unused if context is already an instance of
933
- `Context`
1024
+ e.g. to enable template `context_processors`.
934
1025
  Example:
935
1026
  ```py
936
1027
  MyComponent.render(
@@ -991,11 +1082,26 @@ class Component(
991
1082
  # wraps them in functions.
992
1083
  self._validate_inputs(args or (), kwargs or {}, slots or {})
993
1084
 
1085
+ # Allow to pass down Request object via context.
1086
+ # `context` may be passed explicitly via `Component.render()` and `Component.render_to_response()`,
1087
+ # or implicitly via `{% component %}` tag.
1088
+ if request is None and context:
1089
+ # If the context is `RequestContext`, it has `request` attribute
1090
+ request = getattr(context, "request", None)
1091
+ # Check if this is a nested component and whether parent has request
1092
+ if request is None:
1093
+ parent_id = context.get(_COMPONENT_CONTEXT_KEY, None)
1094
+ if parent_id:
1095
+ parent_comp_ctx = component_context_cache[parent_id]
1096
+ request = parent_comp_ctx.request
1097
+
994
1098
  # Allow to provide no args/kwargs/slots/context
995
1099
  args = cast(ArgsType, args or ())
996
1100
  kwargs = cast(KwargsType, kwargs or {})
997
1101
  slots_untyped = self._normalize_slot_fills(slots or {}, escape_slots_content)
998
1102
  slots = cast(SlotsType, slots_untyped)
1103
+ # Use RequestContext if request is provided, so that child non-component template tags
1104
+ # can access the request object too.
999
1105
  context = context or (RequestContext(request) if request else Context())
1000
1106
 
1001
1107
  # Allow to provide a dict instead of Context
@@ -1027,6 +1133,7 @@ class Component(
1027
1133
  render_dependencies=render_dependencies,
1028
1134
  ),
1029
1135
  is_filled=None,
1136
+ request=request,
1030
1137
  )
1031
1138
 
1032
1139
  # We pass down the components the info about the component's parent.
@@ -1071,6 +1178,8 @@ class Component(
1071
1178
  default_slot=None,
1072
1179
  outer_context=snapshot_context(self.outer_context) if self.outer_context is not None else None,
1073
1180
  registry=self.registry,
1181
+ # Pass down Request object via context
1182
+ request=request,
1074
1183
  post_render_callbacks=post_render_callbacks,
1075
1184
  )
1076
1185
 
@@ -1083,6 +1192,7 @@ class Component(
1083
1192
 
1084
1193
  # Allow to access component input and metadata like component ID from within these hook
1085
1194
  with self._with_metadata(metadata):
1195
+ context_processors_data = self.context_processors_data
1086
1196
  context_data = self.get_context_data(*args, **kwargs)
1087
1197
  # TODO - enable JS and CSS vars - EXPOSE AND DOCUMENT AND MAKE NON-NULL
1088
1198
  js_data = self.get_js_data(*args, **kwargs) if hasattr(self, "get_js_data") else {} # type: ignore
@@ -1107,6 +1217,8 @@ class Component(
1107
1217
 
1108
1218
  with context.update(
1109
1219
  {
1220
+ # Make data from context processors available inside templates
1221
+ **context_processors_data,
1110
1222
  # Private context fields
1111
1223
  _COMPONENT_CONTEXT_KEY: render_id,
1112
1224
  # NOTE: Public API for variables accessible from within a component's template
@@ -1,9 +1,21 @@
1
1
  import copy
2
- from typing import List
2
+ import sys
3
+ from typing import Any, Callable, Dict, List, Tuple
4
+ from weakref import WeakKeyDictionary
3
5
 
4
- from django.template import Context
6
+ from django.http import HttpRequest
7
+ from django.template import Engine
8
+ from django.template.context import BaseContext, Context
5
9
  from django.template.loader_tags import BlockContext
6
10
 
11
+ # We cache the context processors data for each request, so that we don't have to
12
+ # generate it for each component.
13
+ # NOTE: Can't be used as generic in Python 3.8
14
+ if sys.version_info >= (3, 9):
15
+ context_processors_data: WeakKeyDictionary[HttpRequest, Dict[str, Any]] = WeakKeyDictionary()
16
+ else:
17
+ context_processors_data = WeakKeyDictionary()
18
+
7
19
 
8
20
  class CopiedDict(dict):
9
21
  """Dict subclass to identify dictionaries that have been copied with `snapshot_context`"""
@@ -112,3 +124,33 @@ def _copy_block_context(block_context: BlockContext) -> BlockContext:
112
124
  # need to modify the Nodes, but we need to make a copy of the lists.
113
125
  block_context_copy.blocks[key] = val.copy()
114
126
  return block_context_copy
127
+
128
+
129
+ # Django's logic for generating context processors data. The gist is the same as
130
+ # `RequestContext.bind_template()`, but without depending on a Template object.
131
+ # See https://github.com/django/django/blame/2d34ebe49a25d0974392583d5bbd954baf742a32/django/template/context.py#L255
132
+ def gen_context_processors_data(context: BaseContext, request: HttpRequest) -> Dict[str, Any]:
133
+ if request in context_processors_data:
134
+ return context_processors_data[request]
135
+
136
+ # TODO_REMOVE_IN_V2 - In v2, if we still support context processors,
137
+ # it should be set on our settings, so we wouldn't have to get the Engine for that.
138
+ # In v2 it should be also possible to remove RequestContext, and use only Context,
139
+ # since we're internalized the behaviour of RequestContext.
140
+ default_engine = Engine.get_default()
141
+
142
+ # NOTE: Compatibility with `RequestContext`, which accepts an optional
143
+ # `processors` argument.
144
+ request_context_processors: Tuple[Callable[..., Any], ...] = getattr(context, "_processors", ())
145
+
146
+ # This part is same as in `RequestContext.bind_template()`
147
+ processors = default_engine.template_context_processors + request_context_processors
148
+ processors_data = {}
149
+ for processor in processors:
150
+ data = processor(request)
151
+ try:
152
+ processors_data.update(data)
153
+ except TypeError as e:
154
+ raise TypeError(f"Context processor {processor.__qualname__} didn't return a " "dictionary.") from e
155
+
156
+ return processors_data
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.2
2
2
  Name: django_components
3
- Version: 0.129
3
+ Version: 0.130
4
4
  Summary: A way to create simple reusable template components in Django.
5
5
  Author-email: Emil Stenström <emil@emilstenstrom.se>
6
6
  License: MIT