django-components 0.65__tar.gz → 0.66__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 (41) hide show
  1. {django_components-0.65/src/django_components.egg-info → django_components-0.66}/PKG-INFO +15 -2
  2. {django_components-0.65 → django_components-0.66}/README.md +14 -1
  3. {django_components-0.65 → django_components-0.66}/pyproject.toml +1 -1
  4. django_components-0.66/src/django_components/__init__.py +63 -0
  5. {django_components-0.65 → django_components-0.66}/src/django_components/component.py +1 -1
  6. {django_components-0.65 → django_components-0.66}/src/django_components/utils.py +11 -6
  7. {django_components-0.65 → django_components-0.66/src/django_components.egg-info}/PKG-INFO +15 -2
  8. {django_components-0.65 → django_components-0.66}/tests/test_autodiscover.py +43 -1
  9. django_components-0.65/src/django_components/__init__.py +0 -40
  10. {django_components-0.65 → django_components-0.66}/LICENSE +0 -0
  11. {django_components-0.65 → django_components-0.66}/setup.cfg +0 -0
  12. {django_components-0.65 → django_components-0.66}/src/django_components/app_settings.py +0 -0
  13. {django_components-0.65 → django_components-0.66}/src/django_components/apps.py +0 -0
  14. {django_components-0.65 → django_components-0.66}/src/django_components/component_registry.py +0 -0
  15. {django_components-0.65 → django_components-0.66}/src/django_components/logger.py +0 -0
  16. {django_components-0.65 → django_components-0.66}/src/django_components/management/__init__.py +0 -0
  17. {django_components-0.65 → django_components-0.66}/src/django_components/management/commands/__init__.py +0 -0
  18. {django_components-0.65 → django_components-0.66}/src/django_components/management/commands/startcomponent.py +0 -0
  19. {django_components-0.65 → django_components-0.66}/src/django_components/management/commands/upgradecomponent.py +0 -0
  20. {django_components-0.65 → django_components-0.66}/src/django_components/middleware.py +0 -0
  21. {django_components-0.65 → django_components-0.66}/src/django_components/py.typed +0 -0
  22. {django_components-0.65 → django_components-0.66}/src/django_components/safer_staticfiles/__init__.py +0 -0
  23. {django_components-0.65 → django_components-0.66}/src/django_components/safer_staticfiles/apps.py +0 -0
  24. {django_components-0.65 → django_components-0.66}/src/django_components/slots.py +0 -0
  25. {django_components-0.65 → django_components-0.66}/src/django_components/template_loader.py +0 -0
  26. {django_components-0.65 → django_components-0.66}/src/django_components/templatetags/__init__.py +0 -0
  27. {django_components-0.65 → django_components-0.66}/src/django_components/templatetags/component_tags.py +0 -0
  28. {django_components-0.65 → django_components-0.66}/src/django_components/types.py +0 -0
  29. {django_components-0.65 → django_components-0.66}/src/django_components.egg-info/SOURCES.txt +0 -0
  30. {django_components-0.65 → django_components-0.66}/src/django_components.egg-info/dependency_links.txt +0 -0
  31. {django_components-0.65 → django_components-0.66}/src/django_components.egg-info/requires.txt +0 -0
  32. {django_components-0.65 → django_components-0.66}/src/django_components.egg-info/top_level.txt +0 -0
  33. {django_components-0.65 → django_components-0.66}/tests/test_component.py +0 -0
  34. {django_components-0.65 → django_components-0.66}/tests/test_component_as_view.py +0 -0
  35. {django_components-0.65 → django_components-0.66}/tests/test_context.py +0 -0
  36. {django_components-0.65 → django_components-0.66}/tests/test_dependency_rendering.py +0 -0
  37. {django_components-0.65 → django_components-0.66}/tests/test_registry.py +0 -0
  38. {django_components-0.65 → django_components-0.66}/tests/test_settings.py +0 -0
  39. {django_components-0.65 → django_components-0.66}/tests/test_startcomponent_command.py +0 -0
  40. {django_components-0.65 → django_components-0.66}/tests/test_templatetags.py +0 -0
  41. {django_components-0.65 → django_components-0.66}/tests/testutils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.65
3
+ Version: 0.66
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
@@ -25,7 +25,7 @@ Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: Django>=3.2
27
27
 
28
- # django-components
28
+ # <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
29
29
  <a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
30
30
  <a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
31
31
 
@@ -248,6 +248,19 @@ class Calendar(component.Component):
248
248
 
249
249
  And voilá!! We've created our first component.
250
250
 
251
+ ## Autodiscovery
252
+
253
+ By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
254
+
255
+ Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
256
+
257
+ If you are using autodiscovery, keep a few points in mind:
258
+ - Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
259
+ - Components inside the auto-imported files still need to be registered with `@component.register()`
260
+ - Auto-imported component files must be valid Python modules, they must use suffix `.py`, and module name should follow [PEP-8](https://peps.python.org/pep-0008/#package-and-module-names).
261
+
262
+ Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
263
+
251
264
  ## Use the component in a template
252
265
 
253
266
  First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
@@ -1,4 +1,4 @@
1
- # django-components
1
+ # <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
2
2
  <a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
3
3
  <a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
4
4
 
@@ -221,6 +221,19 @@ class Calendar(component.Component):
221
221
 
222
222
  And voilá!! We've created our first component.
223
223
 
224
+ ## Autodiscovery
225
+
226
+ By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
227
+
228
+ Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
229
+
230
+ If you are using autodiscovery, keep a few points in mind:
231
+ - Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
232
+ - Components inside the auto-imported files still need to be registered with `@component.register()`
233
+ - Auto-imported component files must be valid Python modules, they must use suffix `.py`, and module name should follow [PEP-8](https://peps.python.org/pep-0008/#package-and-module-names).
234
+
235
+ Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
236
+
224
237
  ## Use the component in a template
225
238
 
226
239
  First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django_components"
7
- version = "0.65"
7
+ version = "0.66"
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"]
@@ -0,0 +1,63 @@
1
+ import importlib
2
+ import importlib.util
3
+ import os
4
+ from pathlib import Path
5
+
6
+ import django
7
+ from django.conf import settings
8
+ from django.utils.module_loading import autodiscover_modules
9
+
10
+ from django_components.logger import logger
11
+ from django_components.utils import search
12
+
13
+ if django.VERSION < (3, 2):
14
+ default_app_config = "django_components.apps.ComponentsConfig"
15
+
16
+
17
+ def autodiscover() -> None:
18
+ from django_components.app_settings import app_settings
19
+
20
+ if app_settings.AUTODISCOVER:
21
+ # Autodetect a components.py file in each app directory
22
+ autodiscover_modules("components")
23
+
24
+ # Autodetect a <component>.py file in a components dir
25
+ component_filepaths = search(search_glob="**/*.py").matched_files
26
+ logger.debug(f"Autodiscover found {len(component_filepaths)} files in component directories.")
27
+
28
+ for path in component_filepaths:
29
+ # This imports the file and runs it's code. So if the file defines any
30
+ # django components, they will be registered.
31
+ module_name = _filepath_to_python_module(path)
32
+ logger.debug(f'Importing module "{module_name}" (derived from path "{path}")')
33
+ importlib.import_module(module_name)
34
+
35
+ for path_lib in app_settings.LIBRARIES:
36
+ importlib.import_module(path_lib)
37
+
38
+
39
+ def _filepath_to_python_module(file_path: Path) -> str:
40
+ """
41
+ Derive python import path from the filesystem path.
42
+
43
+ Example:
44
+ - If project root is `/path/to/project`
45
+ - And file_path is `/path/to/project/app/components/mycomp.py`
46
+ - Then the path relative to project root is `app/components/mycomp.py`
47
+ - Which we then turn into python import path `app.components.mycomp`
48
+ """
49
+ if hasattr(settings, "BASE_DIR"):
50
+ project_root = str(settings.BASE_DIR)
51
+ else:
52
+ # Fallback for getting the root dir, see https://stackoverflow.com/a/16413955/9788634
53
+ project_root = os.path.abspath(os.path.dirname(__name__))
54
+
55
+ rel_path = os.path.relpath(file_path, start=project_root)
56
+ rel_path_without_suffix = str(Path(rel_path).with_suffix(""))
57
+
58
+ # NOTE: Path normalizes paths to use `/` as separator, while os.path
59
+ # uses `os.path.sep`.
60
+ sep = os.path.sep if os.path.sep in rel_path_without_suffix else "/"
61
+ module_name = rel_path_without_suffix.replace(sep, ".")
62
+
63
+ return module_name
@@ -89,7 +89,7 @@ def _resolve_component_relative_files(attrs: MutableMapping) -> None:
89
89
 
90
90
  # Prepare all possible directories we need to check when searching for
91
91
  # component's template and media files
92
- components_dirs = search()
92
+ components_dirs = search().searched_dirs
93
93
 
94
94
  # Get the directory where the component class is defined
95
95
  try:
@@ -1,13 +1,18 @@
1
1
  import glob
2
2
  from pathlib import Path
3
- from typing import List, Optional, Union
3
+ from typing import List, NamedTuple, Optional
4
4
 
5
5
  from django.template.engine import Engine
6
6
 
7
7
  from django_components.template_loader import Loader
8
8
 
9
9
 
10
- def search(search_glob: Optional[str] = None, engine: Optional[Engine] = None) -> Union[List[str], List[Path]]:
10
+ class SearchResult(NamedTuple):
11
+ searched_dirs: List[Path]
12
+ matched_files: List[Path]
13
+
14
+
15
+ def search(search_glob: Optional[str] = None, engine: Optional[Engine] = None) -> SearchResult:
11
16
  """
12
17
  Search for directories that may contain components.
13
18
 
@@ -22,11 +27,11 @@ def search(search_glob: Optional[str] = None, engine: Optional[Engine] = None) -
22
27
  dirs = loader.get_dirs()
23
28
 
24
29
  if search_glob is None:
25
- return dirs
30
+ return SearchResult(searched_dirs=dirs, matched_files=[])
26
31
 
27
- component_filenames: List[str] = []
32
+ component_filenames: List[Path] = []
28
33
  for directory in dirs:
29
34
  for path in glob.iglob(str(Path(directory) / search_glob), recursive=True):
30
- component_filenames.append(path)
35
+ component_filenames.append(Path(path))
31
36
 
32
- return component_filenames
37
+ return SearchResult(searched_dirs=dirs, matched_files=component_filenames)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: django_components
3
- Version: 0.65
3
+ Version: 0.66
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
@@ -25,7 +25,7 @@ Description-Content-Type: text/markdown
25
25
  License-File: LICENSE
26
26
  Requires-Dist: Django>=3.2
27
27
 
28
- # django-components
28
+ # <img src="logo/logo-black-on-white.svg" alt="django-components" style="max-width: 100%; background: white; color: black;">
29
29
  <a href="https://github.com/EmilStenstrom/django-components/actions?query=workflow%3A%22Run+tests%22"><img align="right" src="https://github.com/EmilStenstrom/django-components/workflows/Run%20tests/badge.svg" alt="Show test status"></a>
30
30
  <a href="https://pepy.tech/project/django-components"><img align="right" src="https://pepy.tech/badge/django-components" alt="Show download stats"></a>
31
31
 
@@ -248,6 +248,19 @@ class Calendar(component.Component):
248
248
 
249
249
  And voilá!! We've created our first component.
250
250
 
251
+ ## Autodiscovery
252
+
253
+ By default, the Python files in the `components` app are auto-imported in order to auto-register the components (e.g. `components/button/button.py`).
254
+
255
+ Autodiscovery occurs when Django is loaded, during the `ready` hook of the `apps.py` file.
256
+
257
+ If you are using autodiscovery, keep a few points in mind:
258
+ - Avoid defining any logic on the module-level inside the `components` dir, that you would not want to run anyway.
259
+ - Components inside the auto-imported files still need to be registered with `@component.register()`
260
+ - Auto-imported component files must be valid Python modules, they must use suffix `.py`, and module name should follow [PEP-8](https://peps.python.org/pep-0008/#package-and-module-names).
261
+
262
+ Autodiscovery can be disabled via in the [settings](#disable-autodiscovery).
263
+
251
264
  ## Use the component in a template
252
265
 
253
266
  First load the `component_tags` tag library, then use the `component_[js/css]_dependencies` and `component` tags to render the component to the page.
@@ -1,4 +1,5 @@
1
1
  from pathlib import Path
2
+ from unittest import mock
2
3
 
3
4
  from django.template.engine import Engine
4
5
  from django.urls import include, path
@@ -9,7 +10,7 @@ from .testutils import Django30CompatibleSimpleTestCase as SimpleTestCase
9
10
 
10
11
  # isort: on
11
12
 
12
- from django_components import autodiscover, component
13
+ from django_components import _filepath_to_python_module, autodiscover, component, component_registry
13
14
  from django_components.template_loader import Loader
14
15
 
15
16
  urlpatterns = [
@@ -25,11 +26,17 @@ class TestAutodiscover(SimpleTestCase):
25
26
  del settings.SETTINGS_MODULE # noqa
26
27
 
27
28
  def test_autodiscover_with_components_as_views(self):
29
+ all_components_before = component_registry.registry.all().copy()
30
+
28
31
  try:
29
32
  autodiscover()
30
33
  except component.AlreadyRegistered:
31
34
  self.fail("Autodiscover should not raise AlreadyRegistered exception")
32
35
 
36
+ all_components_after = component_registry.registry.all().copy()
37
+ imported_components_count = len(all_components_after) - len(all_components_before)
38
+ self.assertEqual(imported_components_count, 1)
39
+
33
40
 
34
41
  class TestLoaderSettingsModule(SimpleTestCase):
35
42
  def tearDown(self) -> None:
@@ -116,3 +123,38 @@ class TestBaseDir(SimpleTestCase):
116
123
  Path(__file__).parent.resolve() / "test_structures" / "test_structure_1" / "components",
117
124
  ]
118
125
  self.assertEqual(sorted(dirs), sorted(expected))
126
+
127
+
128
+ class TestFilepathToPythonModule(SimpleTestCase):
129
+ def test_prepares_path(self):
130
+ self.assertEqual(
131
+ _filepath_to_python_module(Path("tests.py")),
132
+ "tests",
133
+ )
134
+ self.assertEqual(
135
+ _filepath_to_python_module(Path("tests/components/relative_file/relative_file.py")),
136
+ "tests.components.relative_file.relative_file",
137
+ )
138
+
139
+ def test_handles_nonlinux_paths(self):
140
+ with mock.patch("os.path.sep", new="//"):
141
+ self.assertEqual(
142
+ _filepath_to_python_module(Path("tests.py")),
143
+ "tests",
144
+ )
145
+
146
+ self.assertEqual(
147
+ _filepath_to_python_module(Path("tests//components//relative_file//relative_file.py")),
148
+ "tests.components.relative_file.relative_file",
149
+ )
150
+
151
+ with mock.patch("os.path.sep", new="\\"):
152
+ self.assertEqual(
153
+ _filepath_to_python_module(Path("tests.py")),
154
+ "tests",
155
+ )
156
+
157
+ self.assertEqual(
158
+ _filepath_to_python_module(Path("tests\\components\\relative_file\\relative_file.py")),
159
+ "tests.components.relative_file.relative_file",
160
+ )
@@ -1,40 +0,0 @@
1
- import importlib
2
- import importlib.util
3
- import sys
4
- from pathlib import Path
5
- from typing import Union
6
-
7
- import django
8
- from django.utils.module_loading import autodiscover_modules
9
-
10
- from django_components.utils import search
11
-
12
- if django.VERSION < (3, 2):
13
- default_app_config = "django_components.apps.ComponentsConfig"
14
-
15
-
16
- def autodiscover() -> None:
17
- from django_components.app_settings import app_settings
18
-
19
- if app_settings.AUTODISCOVER:
20
- # Autodetect a components.py file in each app directory
21
- autodiscover_modules("components")
22
-
23
- # Autodetect a <component>.py file in a components dir
24
- component_filepaths = search(search_glob="**/*.py")
25
- for path in component_filepaths:
26
- import_file(path)
27
-
28
- for path_lib in app_settings.LIBRARIES:
29
- importlib.import_module(path_lib)
30
-
31
-
32
- def import_file(path: Union[str, Path]) -> None:
33
- MODULE_PATH = path
34
- MODULE_NAME = Path(path).stem
35
- spec = importlib.util.spec_from_file_location(MODULE_NAME, MODULE_PATH)
36
- if spec is None:
37
- raise ValueError(f"Cannot import file '{path}' - invalid path")
38
- module = importlib.util.module_from_spec(spec)
39
- sys.modules[spec.name] = module
40
- spec.loader.exec_module(module) # type: ignore