mcms-data 0.1.0__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.
mcms_data/__init__.py ADDED
@@ -0,0 +1,17 @@
1
+ from mcms_data.contexts.base import DataContext
2
+
3
+ from mcms_data.contexts.base import DataContextType
4
+ from mcms_data.contexts.executor import DataContextExecutor
5
+ from mcms_data.contexts.runtime import RuntimeDataContext
6
+ from mcms_data.contexts.result import DataContextResult
7
+
8
+ from mcms_data.expressions.resolver import DataValueResolver
9
+
10
+ __all__ = [
11
+ "DataContext",
12
+ "DataContextType",
13
+ "RuntimeDataContext",
14
+ "DataValueResolver",
15
+ "DataContextExecutor",
16
+ "DataContextResult",
17
+ ]
mcms_data/apps.py ADDED
@@ -0,0 +1,38 @@
1
+ from django.apps import AppConfig
2
+
3
+ from mcms_data.contexts.executor import DataContextExecutor
4
+ from mcms_data.resolvers.resolver import DataResolver
5
+ from mcms_data.contexts.base import DataContextType
6
+
7
+ from mcms_data.resolvers.internal import InternalDataSourceResolver
8
+ from mcms_data.resolvers.context import ContextDataSourceResolver
9
+ from mcms_data.resolvers.json import JsonDataSourceResolver
10
+ from mcms_data.registry import DataRegistry
11
+
12
+
13
+ class MCMSDataConfig(AppConfig):
14
+ default_auto_field = "django.db.models.BigAutoField"
15
+ name = "mcms_data"
16
+
17
+ def ready(self) -> None:
18
+ self._data_registry = DataRegistry()
19
+ self._data_context_executor = DataContextExecutor(
20
+ resolver=DataResolver(
21
+ resolvers=self._build_resolvers(),
22
+ ),
23
+ )
24
+
25
+ def _build_resolvers(self):
26
+ return {
27
+ DataContextType.INTERNAL: InternalDataSourceResolver(self._data_registry),
28
+ DataContextType.CONTEXT: ContextDataSourceResolver(),
29
+ DataContextType.JSON: JsonDataSourceResolver(),
30
+ }
31
+
32
+ @property
33
+ def data_context_executor(self) -> DataContextExecutor:
34
+ return self._data_context_executor
35
+
36
+ @property
37
+ def data_registry(self) -> DataRegistry:
38
+ return self._data_registry
@@ -0,0 +1,11 @@
1
+ from mcms_data.contexts.base import DataContextType
2
+ from mcms_data.contexts.base import DataContext
3
+ from mcms_data.contexts.runtime import RuntimeDataContext
4
+ from mcms_data.contexts.executor import DataContextExecutor
5
+
6
+ __all__ = [
7
+ "DataContextType",
8
+ "DataContext",
9
+ "RuntimeDataContext",
10
+ "DataContextExecutor",
11
+ ]
@@ -0,0 +1,55 @@
1
+ from dataclasses import dataclass
2
+ from enum import StrEnum
3
+ from typing import Any
4
+
5
+
6
+ class DataContextType(StrEnum):
7
+ INTERNAL = "Internal"
8
+ CONTEXT = "Context"
9
+ JSON = "Json"
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class DataContext:
14
+ type: DataContextType
15
+ source: str
16
+ context: str
17
+ query: dict[str, Any] | None = None
18
+
19
+ def __eq__(self, other: "DataContext") -> bool:
20
+ if other is None:
21
+ return False
22
+
23
+ if not isinstance(other, DataContext):
24
+ return NotImplemented
25
+
26
+ return (
27
+ self.type == other.type
28
+ and self.source == other.source
29
+ and self.context == other.context
30
+ and self.query == other.query
31
+ )
32
+
33
+ def serialize(self) -> dict[str, Any]:
34
+ """
35
+ Serialize the DataContext to a dictionary.
36
+
37
+ Returns
38
+ -------
39
+ dict[str, Any]
40
+ Serialized representation of the DataContext.
41
+ """
42
+ return {
43
+ "type": self.type.value,
44
+ "source": self.source,
45
+ "context": self.context,
46
+ "query": self.query,
47
+ }
48
+
49
+ def clone(self):
50
+ return DataContext(
51
+ type=self.type,
52
+ source=self.source,
53
+ context=self.context,
54
+ query=self.query.copy() if self.query else None,
55
+ )
@@ -0,0 +1,71 @@
1
+ from django.db.models import QuerySet
2
+
3
+ from mcms_data.contexts.base import DataContext
4
+ from mcms_data.contexts.result import DataContextResult
5
+ from mcms_data.contexts.runtime import RuntimeDataContext
6
+ from mcms_data.resolvers.resolver import DataResolver
7
+
8
+
9
+ class DataContextExecutor:
10
+ """
11
+ Resolves a data context and creates runtime contexts
12
+ for its descendants.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ resolver: DataResolver,
18
+ ) -> None:
19
+ self._resolver = resolver
20
+
21
+ def execute(
22
+ self,
23
+ context: DataContext,
24
+ runtime_context: RuntimeDataContext,
25
+ ) -> DataContextResult:
26
+ value = self._resolver.resolve(
27
+ context,
28
+ runtime_context,
29
+ )
30
+
31
+ return self._create_result(
32
+ context,
33
+ value,
34
+ runtime_context,
35
+ )
36
+
37
+ def _create_result(
38
+ self,
39
+ context: DataContext,
40
+ value: object,
41
+ runtime_context: RuntimeDataContext,
42
+ ) -> DataContextResult:
43
+ if value is None:
44
+ return DataContextResult.empty()
45
+
46
+ if self._is_collection(value):
47
+ contexts = tuple(
48
+ runtime_context.child(
49
+ context.context,
50
+ item,
51
+ )
52
+ for item in value
53
+ )
54
+
55
+ return DataContextResult.multiple(
56
+ contexts,
57
+ )
58
+
59
+ return DataContextResult.single(
60
+ runtime_context.child(
61
+ context.context,
62
+ value,
63
+ ),
64
+ )
65
+
66
+ @staticmethod
67
+ def _is_collection(value: object) -> bool:
68
+ return isinstance(
69
+ value,
70
+ (list, tuple, QuerySet),
71
+ )
@@ -0,0 +1,68 @@
1
+ """
2
+ Data context execution results.
3
+ """
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from mcms_data.contexts.runtime import RuntimeDataContext
8
+
9
+
10
+ @dataclass(frozen=True, slots=True)
11
+ class DataContextResult:
12
+ """
13
+ Runtime contexts produced by resolving a DataContext.
14
+
15
+ A result may contain zero, one, or multiple runtime contexts.
16
+ """
17
+
18
+ contexts: tuple[RuntimeDataContext, ...]
19
+
20
+ @classmethod
21
+ def empty(cls) -> "DataContextResult":
22
+ """
23
+ Create an empty result.
24
+ """
25
+ return cls(contexts=())
26
+
27
+ @classmethod
28
+ def single(
29
+ cls,
30
+ context: RuntimeDataContext,
31
+ ) -> "DataContextResult":
32
+ """
33
+ Create a result containing a single runtime context.
34
+ """
35
+ return cls(
36
+ contexts=(context,),
37
+ )
38
+
39
+ @classmethod
40
+ def multiple(
41
+ cls,
42
+ contexts: tuple[RuntimeDataContext, ...],
43
+ ) -> "DataContextResult":
44
+ """
45
+ Create a result containing multiple runtime contexts.
46
+ """
47
+ return cls(contexts=contexts)
48
+
49
+ @property
50
+ def is_empty(self) -> bool:
51
+ """
52
+ Return whether the result contains no contexts.
53
+ """
54
+ return not self.contexts
55
+
56
+ @property
57
+ def is_single(self) -> bool:
58
+ """
59
+ Return whether the result contains exactly one context.
60
+ """
61
+ return len(self.contexts) == 1
62
+
63
+ @property
64
+ def is_multiple(self) -> bool:
65
+ """
66
+ Return whether the result contains multiple contexts.
67
+ """
68
+ return len(self.contexts) > 1
@@ -0,0 +1,63 @@
1
+ from mcms_data.exceptions import RuntimeContextError
2
+
3
+ from django.http import HttpRequest
4
+
5
+
6
+ class RuntimeDataContext:
7
+ request: HttpRequest # TODO: Identify how django will pass request values to this variable
8
+
9
+ def __init__(
10
+ self,
11
+ values: dict[str, object] | None = None,
12
+ parent: "RuntimeDataContext | None" = None,
13
+ ) -> None:
14
+ self._values = values or {}
15
+ self._parent = parent
16
+
17
+ def get(self, name: str) -> object:
18
+ if name in self._values:
19
+ return self._values[name]
20
+
21
+ if self._parent is not None:
22
+ return self._parent.get(name)
23
+
24
+ raise RuntimeContextError(name)
25
+
26
+ def get_page(
27
+ self,
28
+ key: str,
29
+ ) -> int:
30
+ try:
31
+ value = self.request.GET.get(
32
+ f"{key}_page",
33
+ "1",
34
+ )
35
+ except AttributeError:
36
+ return 1
37
+
38
+ try:
39
+ page = int(value)
40
+ except ValueError:
41
+ return RuntimeContextError("Page Value must be a valid integer")
42
+
43
+ return max(page, 1)
44
+
45
+ def child(
46
+ self,
47
+ name: str,
48
+ value: object,
49
+ ) -> "RuntimeDataContext":
50
+ return RuntimeDataContext(
51
+ values={name: value},
52
+ parent=self,
53
+ )
54
+
55
+ @property
56
+ def values(self):
57
+ return self._values
58
+
59
+ def __str__(self):
60
+ return str({"values": self._values, "parent": self._parent})
61
+
62
+ def __repr__(self):
63
+ return str({"values": self._values, "parent": self._parent})
@@ -0,0 +1,25 @@
1
+ from mcms_core.exceptions import MCMSError
2
+
3
+
4
+ class DataError(MCMSError):
5
+ """
6
+ Base exception for mcms_data.
7
+ """
8
+
9
+
10
+ class UnsupportedDataModelError(DataError):
11
+ """
12
+ Raised when DataModel is Invalid
13
+ """
14
+
15
+
16
+ class RuntimeContextError(DataError):
17
+ """
18
+ Raised when Runtime Context Encounters an Error
19
+ """
20
+
21
+
22
+ class DataExpressionError(DataError):
23
+ """
24
+ Raised when Data Expression Encounters an Error
25
+ """
File without changes
@@ -0,0 +1,103 @@
1
+ """
2
+ Data expression definitions.
3
+ """
4
+
5
+ from dataclasses import dataclass
6
+
7
+ from mcms_data.contexts.runtime import RuntimeDataContext
8
+ from mcms_data.exceptions import DataExpressionError
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class DataExpression:
13
+ """
14
+ A reference to a value in the runtime data context.
15
+
16
+ Examples
17
+ --------
18
+ --post.title--
19
+ --post.author.name--
20
+ """
21
+
22
+ path: str
23
+
24
+ CLOSURE = "--"
25
+ NOT_MODIFER = "!"
26
+
27
+ @classmethod
28
+ def parse(
29
+ cls,
30
+ value: str,
31
+ ) -> "DataExpression | list[DataExpression | str] | None":
32
+ """
33
+ Parse a string into a data expression.
34
+
35
+ Returns None when the value is not a data expression.
36
+ """
37
+
38
+ if value.count(cls.CLOSURE) > 2:
39
+ return [
40
+ cls(expression) if "." in expression else expression
41
+ for expression in value.split(cls.CLOSURE)
42
+ ]
43
+
44
+ if not (value.startswith(cls.CLOSURE) and value.endswith(cls.CLOSURE)):
45
+ return None
46
+
47
+ path = value[len(cls.CLOSURE) : -len(cls.CLOSURE)].strip()
48
+
49
+ if not path:
50
+ return None
51
+
52
+ return cls(path=path)
53
+
54
+ def resolve(
55
+ self,
56
+ context: RuntimeDataContext | None,
57
+ ) -> object:
58
+ """
59
+ Resolve the expression against a runtime context.
60
+ """
61
+ not_modified = False
62
+ new_path = self.path
63
+
64
+ if self.path.startswith(self.NOT_MODIFER):
65
+ not_modified = True
66
+ new_path = self.path[len(self.NOT_MODIFER) :]
67
+
68
+ parts = new_path.split(".")
69
+
70
+ try:
71
+ value = None
72
+ if context:
73
+ value = context.get(parts[0])
74
+ except Exception:
75
+ raise DataExpressionError("Invalid Attribute")
76
+
77
+ for part in parts[1:]:
78
+ value = self._resolve_part(
79
+ value,
80
+ part,
81
+ )
82
+
83
+ if not_modified:
84
+ value = not value
85
+
86
+ return value
87
+
88
+ @staticmethod
89
+ def _resolve_part(
90
+ value: object,
91
+ part: str,
92
+ ) -> object:
93
+ """
94
+ Resolve a single path component.
95
+ """
96
+
97
+ if isinstance(value, dict):
98
+ return value[part]
99
+
100
+ try:
101
+ return getattr(value, part)
102
+ except Exception:
103
+ raise DataExpressionError("Invalid Data Expression Attribute")
@@ -0,0 +1,59 @@
1
+ """
2
+ Data value resolution.
3
+ """
4
+
5
+ from mcms_data.contexts.runtime import RuntimeDataContext
6
+ from mcms_data.expressions.base import DataExpression
7
+
8
+
9
+ class DataValueResolver:
10
+ """
11
+ Resolves values against a runtime data context.
12
+
13
+ Static values are returned unchanged. Values matching the MCMS
14
+ data-expression syntax are resolved against the runtime context.
15
+ """
16
+
17
+ def resolve(
18
+ self,
19
+ value: object,
20
+ context: RuntimeDataContext | None,
21
+ ) -> object:
22
+ """
23
+ Resolve a value against a runtime context.
24
+
25
+ Parameters
26
+ ----------
27
+ value:
28
+ Value to resolve.
29
+
30
+ context:
31
+ Runtime data context used to resolve expressions.
32
+
33
+ Returns
34
+ -------
35
+ object
36
+ Resolved value, or the original value when it is not
37
+ a data expression.
38
+ """
39
+
40
+ if not isinstance(value, str):
41
+ return value
42
+
43
+ expressions = DataExpression.parse(value)
44
+
45
+ if expressions is None:
46
+ return value
47
+
48
+ if type(expressions) is list:
49
+ result = ""
50
+ if len(expressions) > 1:
51
+ for expression in expressions:
52
+ if type(expression) is str:
53
+ result += expression
54
+ elif type(expression) == DataExpression:
55
+ result += str(expression.resolve(context))
56
+ return result
57
+
58
+ if type(expressions) == DataExpression:
59
+ return expressions.resolve(context)
File without changes
@@ -0,0 +1,18 @@
1
+ from collections.abc import Sequence
2
+ from dataclasses import dataclass
3
+
4
+
5
+ @dataclass(frozen=True, slots=True)
6
+ class Pagination:
7
+ page: int
8
+ per_page: int
9
+ total: int
10
+ pages: int
11
+ has_next: bool
12
+ has_previous: bool
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class PaginatedData:
17
+ items: Sequence[object]
18
+ pagination: Pagination
mcms_data/py.typed ADDED
File without changes
mcms_data/registry.py ADDED
@@ -0,0 +1,89 @@
1
+ """
2
+ Data registry for django-mcms.
3
+
4
+ This module defines the registry responsible for managing all available
5
+ MCMS field types. It extends the generic Registry implementation from
6
+ ``mcms_core`` with behaviour specific to content fields.
7
+ """
8
+
9
+ from typing import Any
10
+ from django.db import models
11
+
12
+ from mcms_core.registry import Registry
13
+
14
+ from mcms_content.fields.base import Field
15
+ from mcms_data.exceptions import UnsupportedDataModelError
16
+
17
+
18
+ class DataRegistry(Registry[type[models.Model]]):
19
+ """
20
+ Registry for MCMS field types.
21
+
22
+ Field types are registered using the identifier defined in their
23
+ metadata.
24
+
25
+ Example
26
+ -------
27
+ >>> registry = DataRegistry()
28
+ >>> registry.register(Posts)
29
+ """
30
+
31
+ def register(
32
+ self,
33
+ name: str,
34
+ model: type[models.Model],
35
+ ) -> None:
36
+ """
37
+ Register a Model type.
38
+
39
+ Parameters
40
+ ----------
41
+ model:
42
+ The field class to register.
43
+ """
44
+ if not issubclass(model, models.Model):
45
+ raise UnsupportedDataModelError(f"{model!r} is not a Model subclass.")
46
+
47
+ super().register(
48
+ name,
49
+ model,
50
+ )
51
+
52
+ def unregister(
53
+ self,
54
+ identifier: str,
55
+ ) -> None:
56
+ """
57
+ Remove a field type from the registry.
58
+
59
+ Parameters
60
+ ----------
61
+ identifier:
62
+ Identifier of the field type.
63
+ """
64
+ super().unregister(identifier)
65
+
66
+ def create(
67
+ self,
68
+ identifier: str,
69
+ **kwargs: Any,
70
+ ) -> Field:
71
+ """
72
+ Create a configured field instance.
73
+
74
+ Parameters
75
+ ----------
76
+ identifier:
77
+ Registered field identifier.
78
+
79
+ **kwargs:
80
+ Arguments forwarded to the field constructor.
81
+
82
+ Returns
83
+ -------
84
+ Field
85
+ A configured field instance.
86
+ """
87
+ model = self.get(identifier)
88
+
89
+ return model(**kwargs)
File without changes
@@ -0,0 +1,38 @@
1
+ """
2
+ Base data source resolver.
3
+ """
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+ from mcms_data.contexts import DataContext
8
+ from mcms_data.contexts import RuntimeDataContext
9
+
10
+
11
+ class DataSourceResolver(ABC):
12
+ """
13
+ Resolves a DataContext into runtime data.
14
+ """
15
+
16
+ @abstractmethod
17
+ def resolve(
18
+ self,
19
+ context: DataContext,
20
+ runtime_context: RuntimeDataContext,
21
+ ) -> object:
22
+ """
23
+ Resolve a data context.
24
+
25
+ Parameters
26
+ ----------
27
+ context:
28
+ Declarative data context definition.
29
+
30
+ runtime_context:
31
+ Current runtime data scope.
32
+
33
+ Returns
34
+ -------
35
+ object
36
+ Resolved data.
37
+ """
38
+ raise NotImplementedError
@@ -0,0 +1,22 @@
1
+ """
2
+ Context data source resolver.
3
+ """
4
+
5
+ from mcms_data.contexts import DataContext
6
+ from mcms_data.contexts.runtime import RuntimeDataContext
7
+ from mcms_data.resolvers.base import DataSourceResolver
8
+ from mcms_data.expressions.resolver import DataValueResolver
9
+
10
+
11
+ class ContextDataSourceResolver(DataSourceResolver):
12
+ """
13
+ Resolves data from an existing runtime context.
14
+ """
15
+
16
+ def resolve(
17
+ self,
18
+ context: DataContext,
19
+ runtime_context: RuntimeDataContext,
20
+ ) -> object:
21
+ resolver = DataValueResolver()
22
+ return resolver.resolve(context.source, runtime_context)
@@ -0,0 +1,35 @@
1
+ """
2
+ Internal data source resolver.
3
+ """
4
+
5
+ from mcms_data.contexts import DataContext
6
+ from mcms_data.contexts.runtime import RuntimeDataContext
7
+ from mcms_data.registry import DataRegistry
8
+ from mcms_data.resolvers.base import DataSourceResolver
9
+ from mcms_data.retrieval.django import DjangoModelDataRetriever
10
+
11
+
12
+ class InternalDataSourceResolver(DataSourceResolver):
13
+ """
14
+ Resolves data from internally registered sources.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ registry: DataRegistry,
20
+ ) -> None:
21
+ self._registry = registry
22
+ self._retriever = DjangoModelDataRetriever()
23
+
24
+ def resolve(
25
+ self,
26
+ context: DataContext,
27
+ runtime_context: RuntimeDataContext,
28
+ ) -> object:
29
+ source = self._registry.get(
30
+ context.source,
31
+ )
32
+
33
+ return self._retriever.retrieve(
34
+ source, query=context.query, runtime_context=runtime_context
35
+ )
@@ -0,0 +1,27 @@
1
+ """
2
+ Context data source resolver.
3
+ """
4
+
5
+ from mcms_data.contexts import DataContext
6
+ from mcms_data.contexts.runtime import RuntimeDataContext
7
+ from mcms_data.resolvers.base import DataSourceResolver
8
+
9
+ from mcms_data.retrieval.json import JsonModelDataRetriever
10
+
11
+
12
+ class JsonDataSourceResolver(DataSourceResolver):
13
+ """
14
+ Resolves data from an existing runtime context.
15
+ """
16
+
17
+ def __init__(self):
18
+ self._reader = JsonModelDataRetriever()
19
+
20
+ def resolve(
21
+ self,
22
+ context: DataContext,
23
+ runtime_context: RuntimeDataContext,
24
+ ) -> object:
25
+ return self._reader.retrieve(
26
+ context.source, query=context.query, runtime_context=runtime_context
27
+ )
@@ -0,0 +1,38 @@
1
+ from mcms_data.contexts.base import (
2
+ DataContext,
3
+ DataContextType,
4
+ )
5
+ from mcms_data.contexts.runtime import RuntimeDataContext
6
+ from mcms_data.resolvers.base import DataSourceResolver
7
+
8
+
9
+ class DataResolver:
10
+ """
11
+ Dispatches data contexts to their appropriate source resolver.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ resolvers: dict[
17
+ DataContextType,
18
+ DataSourceResolver,
19
+ ],
20
+ ) -> None:
21
+ self._resolvers = resolvers
22
+
23
+ def resolve(
24
+ self,
25
+ context: DataContext,
26
+ runtime_context: RuntimeDataContext,
27
+ ) -> object:
28
+ try:
29
+ resolver = self._resolvers.get(context.type)
30
+ except KeyError as exc:
31
+ raise ValueError(
32
+ f"No resolver registered for data context type {context.type!r}."
33
+ ) from exc
34
+
35
+ return resolver.resolve(
36
+ context,
37
+ runtime_context,
38
+ )
File without changes
@@ -0,0 +1,17 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any
3
+
4
+ from mcms_data.contexts.runtime import RuntimeDataContext
5
+
6
+
7
+ class DataRetriever(ABC):
8
+ """Retrieves data from a registered data source."""
9
+
10
+ @abstractmethod
11
+ def retrieve(
12
+ self,
13
+ source: Any,
14
+ query: dict[Any, Any] | None,
15
+ runtime_context: RuntimeDataContext
16
+ ) -> Any:
17
+ raise NotImplementedError
@@ -0,0 +1,57 @@
1
+ from typing import Any
2
+
3
+ from django.db import models
4
+ from django.core.paginator import Paginator
5
+
6
+ from mcms_data.retrieval.base import DataRetriever
7
+ from mcms_data.pagination import PaginatedData, Pagination
8
+ from mcms_data.contexts.runtime import RuntimeDataContext
9
+
10
+
11
+ class DjangoModelDataRetriever(DataRetriever):
12
+ """Retrieves data from Django models."""
13
+
14
+ def retrieve(
15
+ self,
16
+ source: type[models.Model],
17
+ query: dict | None,
18
+ runtime_context: RuntimeDataContext,
19
+ ) -> Any:
20
+ queryset = source.objects.all()
21
+
22
+ # Expected Pagination Query:
23
+ # query={
24
+ # "pagination": {
25
+ # "key": "destinations",
26
+ # "per_page": 12,
27
+ # },
28
+ # }
29
+ # key is used in the http_request to {key}_page parameter
30
+
31
+ pagination_query = (query or {}).get("pagination")
32
+
33
+ if pagination_query is None:
34
+ return queryset
35
+
36
+ per_page = pagination_query.get("per_page", 12)
37
+ key = pagination_query.get("key")
38
+ page = runtime_context.get_page(f"{key}_page")
39
+
40
+ paginator = Paginator(
41
+ queryset,
42
+ per_page,
43
+ )
44
+
45
+ page_object = paginator.get_page(page)
46
+
47
+ return PaginatedData(
48
+ items=tuple(page_object.object_list),
49
+ pagination=Pagination(
50
+ page=page_object.number,
51
+ per_page=per_page,
52
+ total=paginator.count,
53
+ pages=paginator.num_pages,
54
+ has_next=page_object.has_next(),
55
+ has_previous=page_object.has_previous(),
56
+ ),
57
+ )
@@ -0,0 +1,66 @@
1
+ from typing import Any
2
+ import json
3
+
4
+ from django.core.paginator import Paginator
5
+ from django.contrib.staticfiles import finders
6
+
7
+ from mcms_data.retrieval.base import DataRetriever
8
+ from mcms_data.pagination import PaginatedData, Pagination
9
+ from mcms_data.contexts.runtime import RuntimeDataContext
10
+
11
+ from mcms_data.exceptions import RuntimeContextError
12
+
13
+
14
+ class JsonModelDataRetriever(DataRetriever):
15
+ """Retrieves data from JSON File."""
16
+
17
+ def retrieve(
18
+ self,
19
+ source: str,
20
+ query: dict | None,
21
+ runtime_context: RuntimeDataContext,
22
+ ) -> Any:
23
+ try:
24
+ with open(finders.find(source) or source, "r") as file:
25
+ queryset = json.load(file)
26
+ except Exception:
27
+ raise RuntimeContextError(
28
+ f"JSON Data Retriever failed. File '{source}' not found!"
29
+ )
30
+
31
+ # Expected Pagination Query:
32
+ # query={
33
+ # "pagination": {
34
+ # "key": "destinations",
35
+ # "per_page": 12,
36
+ # },
37
+ # }
38
+ # key is used in the http_request to {key}_page parameter
39
+
40
+ pagination_query = (query or {}).get("pagination")
41
+
42
+ if pagination_query is None:
43
+ return queryset
44
+
45
+ per_page = pagination_query.get("per_page", 12)
46
+ key = pagination_query.get("key")
47
+ page = runtime_context.get_page(f"{key}")
48
+
49
+ paginator = Paginator(
50
+ queryset,
51
+ per_page,
52
+ )
53
+
54
+ page_object = paginator.get_page(page)
55
+
56
+ return PaginatedData(
57
+ items=tuple(page_object.object_list),
58
+ pagination=Pagination(
59
+ page=page_object.number,
60
+ per_page=per_page,
61
+ total=paginator.count,
62
+ pages=paginator.num_pages,
63
+ has_next=page_object.has_next(),
64
+ has_previous=page_object.has_previous(),
65
+ ),
66
+ )
mcms_data/settings.py ADDED
File without changes
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.3
2
+ Name: mcms-data
3
+ Version: 0.1.0
4
+ Summary: Provides declarative data binding and runtime data resolution for MCMS
5
+ Author: MikemathuKE
6
+ Author-email: MikemathuKE <michaelmathu6@gmail.com>
7
+ Requires-Dist: mcms-core
8
+ Requires-Python: >=3.13
9
+ Description-Content-Type: text/markdown
10
+
11
+ # MCMS Data
12
+
13
+ `mcms_data` provides declarative data binding and runtime data resolution for MCMS. It resolves data contexts and expressions before component rendering, keeping components independent of data sources and persistence mechanisms.
14
+
15
+ ## Responsibilities
16
+
17
+ - Define the `DataContext` abstraction.
18
+ - Resolve named data sources through `DataRegistry`.
19
+ - Resolve internal data sources through registered Django models.
20
+ - Parse and resolve data expressions using the `--expression--` syntax.
21
+ - Build runtime data contexts and support nested context scopes.
22
+ - Resolve both single objects and collections through the same context mechanism.
23
+ - Apply query definitions when retrieving data, according to the implemented query schema.
24
+ - Keep data retrieval and binding resolution outside component definitions and the renderer.
25
+
26
+ ## Data context
27
+
28
+ A data context identifies the source type, registered source name, runtime context name, and query.
29
+
30
+ ```json
31
+ {
32
+ "type": "Internal",
33
+ "source": "posts",
34
+ "context": "post",
35
+ "query": {}
36
+ }
37
+ ```
38
+
39
+ The initial source type is `Internal`. The architecture leaves room for additional source types, but external source types such as REST are not part of the initial implementation scope.
40
+
41
+ ## Data registry
42
+
43
+ `DataRegistry` maps stable source names to registered objects, typically Django models:
44
+
45
+ ```python
46
+ data_registry.register("posts", Post)
47
+ ```
48
+
49
+ The registry does not own Django model registration, migrations, persistence, or model construction.
50
+
51
+ ## Expressions and nested contexts
52
+
53
+ Expressions use the form:
54
+
55
+ ```text
56
+ --post.title--
57
+ ```
58
+
59
+ A nested context extends the runtime scope established by its parent. Descendants can resolve values from the current context and, where supported by the runtime scope rules, ancestor contexts.
60
+
61
+ Single objects and collections share the same data-context abstraction. When a source resolves to a collection, the children of the data context act as the item template and are rendered for each item.
62
+
63
+ ## Resolution flow
64
+
65
+ ```text
66
+ DataContext
67
+ |
68
+ v
69
+ DataRegistry
70
+ |
71
+ v
72
+ Internal source resolver
73
+ |
74
+ v
75
+ Runtime data context
76
+ |
77
+ v
78
+ Expression resolver
79
+ |
80
+ v
81
+ Resolved component values
82
+ |
83
+ v
84
+ mcms_render
85
+ ```
86
+
87
+ Components do not perform ORM queries or retrieve data directly. The persisted render structure remains declarative; resolved values are runtime concerns.
88
+
89
+ ## Architectural integrations
90
+
91
+ | Package / system | Relationship |
92
+ |---|---|
93
+ | `mcms_core` | Shared registry and exception infrastructure |
94
+ | Django models | Initial internal data source objects |
95
+
96
+ ## Scope and limitations
97
+
98
+ The ADRs establish the context and expression model but leave the complete query schema open. The initial source type is `Internal`; REST and other external providers are future possibilities. Authentication/authorization, caching, transformations, mutation, and mixed-string interpolation are not defined by the initial decision.
99
+
100
+ ## Application configuration
101
+
102
+ No specific global `apps` variable or data-root setting is named in the data ADRs. Document actual host-application registration and settings after verifying the implementation.
103
+
104
+ ## Dependencies
105
+
106
+ ### Architectural integrations
107
+
108
+ See the integration table. In particular, `mcms_data` depends conceptually on the common registry contract and Django model metadata for the initial `Internal` source implementation.
109
+
110
+ ### Python distribution dependencies
111
+
112
+ All MCMS Packages rely on django
113
+
114
+ ## Development
115
+
116
+ ```bash
117
+ uv run pytest packages/mcms-data/tests
118
+ ```
119
+
120
+ Run Ruff and mypy using the repository's configured commands.
@@ -0,0 +1,29 @@
1
+ mcms_data/__init__.py,sha256=WfsL3yt8BMQdPi3ankmyS6tSx37AdYM7kNRV7s0T_Js,514
2
+ mcms_data/apps.py,sha256=Uwr3W4KjNrUbz1efvMEFaXBDtRWS6sI3gB8gZnMMtuc,1324
3
+ mcms_data/contexts/__init__.py,sha256=5Igd66BaY-1BDCOv0v9uBkFyN6Flusmtl4AHPM0920c,339
4
+ mcms_data/contexts/base.py,sha256=fFfwH5hyYAyApKyPGgSOKwAV14PR3I5X7sIEprOX6PY,1394
5
+ mcms_data/contexts/executor.py,sha256=qcE7REGbnORVr2rCm78S-Ez2Z87XhfJShvYKoS63d5Q,1797
6
+ mcms_data/contexts/result.py,sha256=xjW89V87rEhDwzdL-BoRSnXnNhN1-LszxGdlS9sxAuQ,1625
7
+ mcms_data/contexts/runtime.py,sha256=gs6z_wNPJFNhuPvU110E5-zv3V_BpZn-kqj9PT4vCoY,1599
8
+ mcms_data/exceptions.py,sha256=vFYHT61B1aaGoDV1U1WYuElGBLO3O-G03AlYbASmjOk,463
9
+ mcms_data/expressions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ mcms_data/expressions/base.py,sha256=KESLm2fCuDbOKfAWr8FkBLb56ASBortHvEsKwOp7t6c,2469
11
+ mcms_data/expressions/resolver.py,sha256=xNcAusmRSuk55FziPGLOiwgLVPCAgIhMMkKPzxaMHTU,1599
12
+ mcms_data/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
13
+ mcms_data/pagination.py,sha256=gOr1FxcAbvNgxsJK1rS4ohHGE44dmk3D7jthlvb-tOc,363
14
+ mcms_data/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
+ mcms_data/registry.py,sha256=SzgohHoobAA7FKSIWnZvTbp0lWj2eQhDNkw2sP4XSIM,2044
16
+ mcms_data/resolvers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
17
+ mcms_data/resolvers/base.py,sha256=dsfJ1g4OoG6HxOfa-SHTJ2Q9SuDHhYjmLuOCPCOipyE,779
18
+ mcms_data/resolvers/context.py,sha256=OiNZkDmqm3Q8cUPdnK-j_NfPrisAjfyVenw_1J72vus,630
19
+ mcms_data/resolvers/internal.py,sha256=FzeLCdfgs5se3KcEpB5BZR2ApVJy60ECrnYpYeBPovI,957
20
+ mcms_data/resolvers/json.py,sha256=kg08oC-Y-178sMAJbqRipih996u2jJxSUGBp_nYqTZI,730
21
+ mcms_data/resolvers/resolver.py,sha256=n8H0TR_khWMMYFzyxEsmRvc6_Neae8A9FZdqs94SjpU,971
22
+ mcms_data/retrieval/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ mcms_data/retrieval/base.py,sha256=V0NvolK9sftWCd9obJMhjuo6P2Im1OeEP4OoZxexdok,423
24
+ mcms_data/retrieval/django.py,sha256=derEBPsxazVLEJq3D-C23z17EvU_YkHEkZPm3tEDh84,1688
25
+ mcms_data/retrieval/json.py,sha256=BNRq4LDpXeYU42YQEYYbfIJQ-_BHz7bSlfUTNKWV8TI,1992
26
+ mcms_data/settings.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
27
+ mcms_data-0.1.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
28
+ mcms_data-0.1.0.dist-info/METADATA,sha256=Oj0ByxPc5znY0Mwq65pnwp8owmjYW_aMX6HVGYEGI-I,3863
29
+ mcms_data-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any