formaxapi 0.1.8__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.
Files changed (41) hide show
  1. fastschema/__init__.py +19 -0
  2. fastschema/core/__init__.py +13 -0
  3. fastschema/core/field_config.py +49 -0
  4. fastschema/core/metaclass.py +96 -0
  5. fastschema/core/model_factory.py +189 -0
  6. fastschema/core/route_base.py +70 -0
  7. fastschema/core/route_decorator.py +70 -0
  8. fastschema/core/route_field.py +135 -0
  9. fastschema/core/self_derived.py +27 -0
  10. formaxapi/__init__.py +19 -0
  11. formaxapi/core/__init__.py +13 -0
  12. formaxapi/core/field_config.py +49 -0
  13. formaxapi/core/metaclass.py +96 -0
  14. formaxapi/core/model_factory.py +189 -0
  15. formaxapi/core/route_base.py +70 -0
  16. formaxapi/core/route_decorator.py +70 -0
  17. formaxapi/core/route_field.py +135 -0
  18. formaxapi/core/self_derived.py +27 -0
  19. formaxapi-0.1.8.dist-info/METADATA +880 -0
  20. formaxapi-0.1.8.dist-info/RECORD +41 -0
  21. formaxapi-0.1.8.dist-info/WHEEL +5 -0
  22. formaxapi-0.1.8.dist-info/licenses/LICENSE +201 -0
  23. formaxapi-0.1.8.dist-info/top_level.txt +1 -0
  24. modelrouter/__init__.py +19 -0
  25. modelrouter/core/__init__.py +13 -0
  26. modelrouter/core/field_config.py +49 -0
  27. modelrouter/core/metaclass.py +96 -0
  28. modelrouter/core/model_factory.py +189 -0
  29. modelrouter/core/route_base.py +70 -0
  30. modelrouter/core/route_decorator.py +70 -0
  31. modelrouter/core/route_field.py +135 -0
  32. modelrouter/core/self_derived.py +27 -0
  33. routex/__init__.py +19 -0
  34. routex/core/__init__.py +13 -0
  35. routex/core/field_config.py +49 -0
  36. routex/core/metaclass.py +96 -0
  37. routex/core/model_factory.py +189 -0
  38. routex/core/route_base.py +70 -0
  39. routex/core/route_decorator.py +70 -0
  40. routex/core/route_field.py +135 -0
  41. routex/core/self_derived.py +27 -0
@@ -0,0 +1,41 @@
1
+ fastschema/__init__.py,sha256=GpBBkc8gWXWOLbprGneu0f2ORRHsMMh_PLml3Wh8mvc,638
2
+ fastschema/core/__init__.py,sha256=NeeBvdGdBiTNBKBpa-x_Dsqe6Lgvky5UJLoG1IgaHFQ,468
3
+ fastschema/core/field_config.py,sha256=MLGCrRTAyDX5V-5oEO8E7j8r1SU2oty0_NssOH0RB4c,1375
4
+ fastschema/core/metaclass.py,sha256=kEGbDbsATJUvpDCVN5xGVXdXqC-UVSxu9Z4RVchtssg,3124
5
+ fastschema/core/model_factory.py,sha256=fC6UEC4nJ-jIQzsEzQqqX-Grgbv97xkYryVkbcLo0LY,7708
6
+ fastschema/core/route_base.py,sha256=cSH-k_MOpdKwn_95z2tzfTMJ-l9j5Oggk_fHwCtp084,2609
7
+ fastschema/core/route_decorator.py,sha256=Fu6ljTAdzAHxIimueY9ogKPSB5qXTUKStJw1F6zk7PM,2095
8
+ fastschema/core/route_field.py,sha256=h0eDO9r3pRYobMk2zbhMR-D6PPx7m7_fpIHZLlql4sE,5706
9
+ fastschema/core/self_derived.py,sha256=GHVisNGm7IMvAgGauDHqNptwkIU8kh8_oRHoER6nIU0,1039
10
+ formaxapi/__init__.py,sha256=GpBBkc8gWXWOLbprGneu0f2ORRHsMMh_PLml3Wh8mvc,638
11
+ formaxapi/core/__init__.py,sha256=NeeBvdGdBiTNBKBpa-x_Dsqe6Lgvky5UJLoG1IgaHFQ,468
12
+ formaxapi/core/field_config.py,sha256=MLGCrRTAyDX5V-5oEO8E7j8r1SU2oty0_NssOH0RB4c,1375
13
+ formaxapi/core/metaclass.py,sha256=kEGbDbsATJUvpDCVN5xGVXdXqC-UVSxu9Z4RVchtssg,3124
14
+ formaxapi/core/model_factory.py,sha256=fC6UEC4nJ-jIQzsEzQqqX-Grgbv97xkYryVkbcLo0LY,7708
15
+ formaxapi/core/route_base.py,sha256=cSH-k_MOpdKwn_95z2tzfTMJ-l9j5Oggk_fHwCtp084,2609
16
+ formaxapi/core/route_decorator.py,sha256=Fu6ljTAdzAHxIimueY9ogKPSB5qXTUKStJw1F6zk7PM,2095
17
+ formaxapi/core/route_field.py,sha256=h0eDO9r3pRYobMk2zbhMR-D6PPx7m7_fpIHZLlql4sE,5706
18
+ formaxapi/core/self_derived.py,sha256=GHVisNGm7IMvAgGauDHqNptwkIU8kh8_oRHoER6nIU0,1039
19
+ formaxapi-0.1.8.dist-info/licenses/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
20
+ modelrouter/__init__.py,sha256=GpBBkc8gWXWOLbprGneu0f2ORRHsMMh_PLml3Wh8mvc,638
21
+ modelrouter/core/__init__.py,sha256=NeeBvdGdBiTNBKBpa-x_Dsqe6Lgvky5UJLoG1IgaHFQ,468
22
+ modelrouter/core/field_config.py,sha256=MLGCrRTAyDX5V-5oEO8E7j8r1SU2oty0_NssOH0RB4c,1375
23
+ modelrouter/core/metaclass.py,sha256=kEGbDbsATJUvpDCVN5xGVXdXqC-UVSxu9Z4RVchtssg,3124
24
+ modelrouter/core/model_factory.py,sha256=fC6UEC4nJ-jIQzsEzQqqX-Grgbv97xkYryVkbcLo0LY,7708
25
+ modelrouter/core/route_base.py,sha256=cSH-k_MOpdKwn_95z2tzfTMJ-l9j5Oggk_fHwCtp084,2609
26
+ modelrouter/core/route_decorator.py,sha256=Fu6ljTAdzAHxIimueY9ogKPSB5qXTUKStJw1F6zk7PM,2095
27
+ modelrouter/core/route_field.py,sha256=h0eDO9r3pRYobMk2zbhMR-D6PPx7m7_fpIHZLlql4sE,5706
28
+ modelrouter/core/self_derived.py,sha256=GHVisNGm7IMvAgGauDHqNptwkIU8kh8_oRHoER6nIU0,1039
29
+ routex/__init__.py,sha256=GpBBkc8gWXWOLbprGneu0f2ORRHsMMh_PLml3Wh8mvc,638
30
+ routex/core/__init__.py,sha256=NeeBvdGdBiTNBKBpa-x_Dsqe6Lgvky5UJLoG1IgaHFQ,468
31
+ routex/core/field_config.py,sha256=MLGCrRTAyDX5V-5oEO8E7j8r1SU2oty0_NssOH0RB4c,1375
32
+ routex/core/metaclass.py,sha256=kEGbDbsATJUvpDCVN5xGVXdXqC-UVSxu9Z4RVchtssg,3124
33
+ routex/core/model_factory.py,sha256=fC6UEC4nJ-jIQzsEzQqqX-Grgbv97xkYryVkbcLo0LY,7708
34
+ routex/core/route_base.py,sha256=cSH-k_MOpdKwn_95z2tzfTMJ-l9j5Oggk_fHwCtp084,2609
35
+ routex/core/route_decorator.py,sha256=Fu6ljTAdzAHxIimueY9ogKPSB5qXTUKStJw1F6zk7PM,2095
36
+ routex/core/route_field.py,sha256=h0eDO9r3pRYobMk2zbhMR-D6PPx7m7_fpIHZLlql4sE,5706
37
+ routex/core/self_derived.py,sha256=GHVisNGm7IMvAgGauDHqNptwkIU8kh8_oRHoER6nIU0,1039
38
+ formaxapi-0.1.8.dist-info/METADATA,sha256=44nk0xQFy8kdY6q3CMwNqZxnQuBdBLPZ9Wlm-HcJKek,23308
39
+ formaxapi-0.1.8.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
40
+ formaxapi-0.1.8.dist-info/top_level.txt,sha256=FtrKN1Y1R1_SpY4lAG1AB3fDP0qn2Us1Wap8tvdQZrk,10
41
+ formaxapi-0.1.8.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ formaxapi
@@ -0,0 +1,19 @@
1
+ """
2
+ framework - Class-based routing with dynamic Pydantic model generation for FastAPI.
3
+
4
+ Routes defined inside the class with @route decorator.
5
+ Typed input via UserRoute.schema() — request body auto-validated.
6
+ SelfDerivedModel for bulk operations — derive schemas from own fields.
7
+ """
8
+
9
+ from .core import (
10
+ FieldConfig, Chain, RouteField, FieldInfo, SelfDerivedModel,
11
+ RouteBase, ModelFactory, RouteMetaclass,
12
+ route, route_factory,
13
+ )
14
+
15
+ __all__ = [
16
+ 'FieldConfig', 'Chain', 'RouteField', 'FieldInfo', 'SelfDerivedModel',
17
+ 'RouteBase', 'ModelFactory', 'RouteMetaclass',
18
+ 'route', 'route_factory',
19
+ ]
@@ -0,0 +1,13 @@
1
+ from .field_config import FieldConfig, Chain
2
+ from .route_field import RouteField, FieldInfo
3
+ from .self_derived import SelfDerivedModel
4
+ from .route_base import RouteBase
5
+ from .model_factory import ModelFactory
6
+ from .metaclass import RouteMetaclass
7
+ from .route_decorator import route, route_factory
8
+
9
+ __all__ = [
10
+ 'FieldConfig', 'Chain', 'RouteField', 'FieldInfo', 'SelfDerivedModel',
11
+ 'RouteBase', 'ModelFactory', 'RouteMetaclass',
12
+ 'route', 'route_factory',
13
+ ]
@@ -0,0 +1,49 @@
1
+ """FieldConfig - Base class for schema type configurations."""
2
+
3
+ from __future__ import annotations
4
+ from typing import Any, Callable
5
+
6
+
7
+ _UNSET = object()
8
+
9
+
10
+ class Chain:
11
+ """Compose multiple functions to run sequentially on a field value."""
12
+
13
+ def __init__(self, *funcs: Callable):
14
+ self.funcs = funcs
15
+
16
+ def __call__(self, v: Any) -> Any:
17
+ result = v
18
+ for func in self.funcs:
19
+ result = func(result)
20
+ return result
21
+
22
+
23
+ class FieldConfig:
24
+ """Extend to define schema types."""
25
+
26
+ required: bool = False
27
+ default: Any = _UNSET
28
+ default_factory: Callable | None = None
29
+ alias: str | None = None
30
+ description: str | None = None
31
+ type_override: type | None = None
32
+ exclude: bool = False
33
+ frozen: bool = False
34
+ apply_func: Callable | None = None
35
+ before: bool = True # True = before validators, False = after validators
36
+ metadata: dict | None = None
37
+
38
+ def __init__(self, **overrides):
39
+ for key, value in overrides.items():
40
+ if hasattr(self, key) or key in self.__class__.__dict__:
41
+ setattr(self, key, value)
42
+
43
+ def __repr__(self):
44
+ attrs = {k: v for k, v in self.__dict__.items() if v is not _UNSET and v is not None and v is not False}
45
+ return f"{self.__name__}({attrs})"
46
+
47
+ @property
48
+ def __name__(self):
49
+ return self.__class__.__name__
@@ -0,0 +1,96 @@
1
+ """RouteMetaclass - Collects fields and discovers schema types."""
2
+
3
+ from __future__ import annotations
4
+ import sys
5
+ import typing
6
+ from typing import get_type_hints, ClassVar, get_origin, get_args
7
+ from .route_field import RouteField, FieldInfo
8
+
9
+ try:
10
+ from sqlmodel.main import SQLModelMetaclass as _BaseMetaclass
11
+ except ImportError:
12
+ from pydantic._internal._model_construction import ModelMetaclass as _BaseMetaclass
13
+
14
+
15
+ def _resolve_annotations(cls: type) -> dict[str, type]:
16
+ try:
17
+ module = sys.modules.get(cls.__module__)
18
+ if not module:
19
+ return {}
20
+ return get_type_hints(cls, localns=vars(module))
21
+ except Exception:
22
+ return getattr(cls, '__annotations__', {})
23
+
24
+
25
+ def _has_pydantic_base(bases: tuple) -> bool:
26
+ for base in bases:
27
+ if getattr(base, '__pydantic_complete__', False):
28
+ return True
29
+ if getattr(base, '__pydantic_validator__', None) is not None:
30
+ return True
31
+ return False
32
+
33
+
34
+ def _is_classvar(annotation) -> bool:
35
+ origin = get_origin(annotation)
36
+ if origin is ClassVar:
37
+ return True
38
+ if isinstance(annotation, str):
39
+ return 'ClassVar' in annotation
40
+ return False
41
+
42
+
43
+ def _unwrap_classvar(annotation):
44
+ if _is_classvar(annotation):
45
+ args = get_args(annotation)
46
+ if args:
47
+ return args[0]
48
+ return str
49
+ return annotation
50
+
51
+
52
+ class RouteMetaclass(_BaseMetaclass):
53
+ def __new__(mcs, cls_name, bases, namespace, **kwargs):
54
+ if _has_pydantic_base(bases):
55
+ cls = super().__new__(mcs, cls_name, bases, namespace, **kwargs)
56
+ else:
57
+ cls = type.__new__(mcs, cls_name, bases, namespace)
58
+
59
+ fields = {}
60
+ for base in bases:
61
+ bf = getattr(base, '_fields', None)
62
+ if bf:
63
+ fields.update(bf)
64
+
65
+ resolved = _resolve_annotations(cls)
66
+
67
+ # Collect RouteField entries
68
+ for attr_name, annotation in resolved.items():
69
+ attr_value = namespace.get(attr_name)
70
+ if isinstance(attr_value, RouteField):
71
+ # Unwrap ClassVar[str] -> str for the schema
72
+ field_type = _unwrap_classvar(annotation) if _is_classvar(annotation) else annotation
73
+ fields[attr_name] = attr_value.to_field_info(attr_name, field_type)
74
+
75
+ # Collect ClassVar fields (not RouteField, but user wants them in schemas)
76
+ for attr_name, annotation in resolved.items():
77
+ if attr_name in fields:
78
+ continue
79
+ if _is_classvar(annotation) and attr_name in namespace:
80
+ inner_type = _unwrap_classvar(annotation)
81
+ field_info = FieldInfo(
82
+ name=attr_name,
83
+ annotation=inner_type,
84
+ default=namespace.get(attr_name, None),
85
+ configs={},
86
+ )
87
+ fields[attr_name] = field_info
88
+
89
+ cls._fields = fields
90
+
91
+ schema_types = set()
92
+ for info in fields.values():
93
+ schema_types.update(info.configs.keys())
94
+ cls._schema_types = schema_types
95
+
96
+ return cls
@@ -0,0 +1,189 @@
1
+ """ModelFactory - Generates Pydantic models from FieldInfo + schema type."""
2
+
3
+ from __future__ import annotations
4
+ from types import NoneType
5
+ from typing import Literal
6
+ from pydantic import BaseModel, Field, create_model, ConfigDict
7
+ from pydantic import field_validator as pv_field_validator
8
+ from pydantic import model_validator as pv_model_validator
9
+ from .route_field import FieldInfo
10
+ from .self_derived import SelfDerivedModel
11
+ from .field_config import _UNSET
12
+
13
+
14
+ class ModelFactory:
15
+
16
+ @staticmethod
17
+ def create(fields, schema_type, model_name="GeneratedModel",
18
+ forbid_extra=True, include_fields=None, exclude_fields=None,
19
+ as_literal=False, route_cls=None) -> type[BaseModel]:
20
+ skip = set(exclude_fields or [])
21
+ only = set(include_fields) if include_fields else None
22
+
23
+ if as_literal:
24
+ names = [n for n, info in fields.items()
25
+ if n not in skip and (only is None or n in only)
26
+ and info.has_config(schema_type)
27
+ and not info.get_config(schema_type).exclude]
28
+ return Literal[tuple(names)]
29
+
30
+ model_fields = {}
31
+ apply_funcs = {}
32
+ for name, info in fields.items():
33
+ if name in skip or (only is not None and name not in only):
34
+ continue
35
+ config = info.get_config(schema_type)
36
+ if config is None or config.exclude:
37
+ continue
38
+
39
+ ftype = config.type_override or info.annotation
40
+
41
+ if isinstance(ftype, str):
42
+ import typing
43
+ ftype = typing._eval_type(typing.ForwardRef(ftype), globals(), None)
44
+
45
+ fdefault = ModelFactory._resolve_default(config, info)
46
+
47
+ # Resolve SelfDerivedModel
48
+ if isinstance(fdefault, SelfDerivedModel) and route_cls:
49
+ ftype, fdefault = ModelFactory._resolve_self_derived(fdefault, route_cls)
50
+
51
+ if fdefault is not None and fdefault is not ...:
52
+ if NoneType not in (getattr(ftype, '__args__', ()) or ()):
53
+ ftype = ftype | None
54
+
55
+ # Start with RouteField's Pydantic Field kwargs
56
+ fk = dict(info.field_info_kwargs) if info.field_info_kwargs else {}
57
+
58
+ # Remove 'default' from kwargs — we pass it as positional arg
59
+ fk.pop('default', None)
60
+ fk.pop('default_factory', None)
61
+
62
+ # Config-level overrides take precedence
63
+ if info.alias and 'alias' not in fk:
64
+ fk['alias'] = info.alias
65
+ desc = config.description or info.description
66
+ if desc and 'description' not in fk:
67
+ fk['description'] = desc
68
+ if config.frozen and 'frozen' not in fk:
69
+ fk['frozen'] = True
70
+ if config.metadata:
71
+ fk.update(config.metadata)
72
+
73
+ # Pass constraint kwargs (max_length, min_length, gt, etc.) from RouteField
74
+ field_metadata = info.metadata if hasattr(info, 'metadata') and info.metadata else None
75
+ if field_metadata and isinstance(field_metadata, dict):
76
+ fk.update(field_metadata)
77
+
78
+ model_fields[name] = (ftype, Field(fdefault, **fk))
79
+
80
+ if config.apply_func is not None:
81
+ func = config.apply_func
82
+ if hasattr(func, '__func__'):
83
+ func = func.__func__
84
+ apply_funcs[name] = (func, 'before' if config.before else 'after')
85
+
86
+ validator_base = ModelFactory._create_validator_base(route_cls, fields, schema_type, apply_funcs)
87
+ model_module = route_cls.__module__ if route_cls else __name__
88
+
89
+ if validator_base:
90
+ model = create_model(
91
+ model_name,
92
+ __base__=validator_base,
93
+ __config__=ConfigDict(extra='forbid' if forbid_extra else 'ignore'),
94
+ __module__=model_module,
95
+ **model_fields,
96
+ )
97
+ else:
98
+ model = create_model(
99
+ model_name,
100
+ __config__=ConfigDict(extra='forbid' if forbid_extra else 'ignore'),
101
+ __module__=model_module,
102
+ **model_fields,
103
+ )
104
+
105
+ try:
106
+ model.model_rebuild(force=True)
107
+ except Exception:
108
+ pass
109
+
110
+ return model
111
+
112
+ @staticmethod
113
+ def _create_validator_base(route_cls, fields, schema_type, apply_funcs=None):
114
+ """Create a base class with validators from route_cls and apply_func."""
115
+ apply_funcs = apply_funcs or {}
116
+ namespace = {}
117
+
118
+ # Collect validators from route_cls
119
+ if route_cls and getattr(route_cls, '__pydantic_complete__', False):
120
+ decorators = getattr(route_cls, '__pydantic_decorators__', None)
121
+ if decorators:
122
+ for name, dec in decorators.field_validators.items():
123
+ func = getattr(route_cls, name, None)
124
+ if func is None:
125
+ continue
126
+ raw_func = getattr(func, '__func__', func)
127
+ mode = dec.info.mode or 'before'
128
+ for field_name in dec.info.fields:
129
+ validator_name = f'_validator_{field_name}_{mode}'
130
+ namespace[validator_name] = pv_field_validator(field_name, mode=mode, check_fields=False)(raw_func)
131
+
132
+ for name, dec in decorators.model_validators.items():
133
+ if name == 'fill_back_refs':
134
+ continue
135
+ func = getattr(route_cls, name, None)
136
+ if func is None:
137
+ continue
138
+ raw_func = getattr(func, '__func__', func)
139
+ namespace[f'_model_validator_{name}'] = pv_model_validator(mode=dec.info.mode)(raw_func)
140
+
141
+ # Create validators from apply_func
142
+ for field_name, (func, mode) in apply_funcs.items():
143
+ validator_name = f'_apply_func_{field_name}_{mode}'
144
+ def _make_validator(f):
145
+ def validator(cls, v):
146
+ return f(v)
147
+ return validator
148
+ v = _make_validator(func)
149
+ v.__qualname__ = validator_name
150
+ namespace[validator_name] = pv_field_validator(field_name, mode=mode, check_fields=False)(v)
151
+
152
+ if namespace:
153
+ base_name = f'{route_cls.__name__}Validators' if route_cls else 'Validators'
154
+ return type(base_name, (BaseModel,), namespace)
155
+ return None
156
+
157
+ @staticmethod
158
+ def _resolve_default(config, info):
159
+ if config.default is not _UNSET:
160
+ return config.default
161
+ if config.default_factory is not None:
162
+ return config.default_factory
163
+ if info.default is not _UNSET:
164
+ return info.default
165
+ if info.default_factory is not None:
166
+ return info.default_factory
167
+ if config.required:
168
+ return ...
169
+ return ...
170
+
171
+ @staticmethod
172
+ def _resolve_self_derived(sdm, route_cls):
173
+ derived = route_cls.schema(
174
+ sdm.schema,
175
+ include_fields=sdm.include_fields,
176
+ exclude_fields=sdm.exclude_fields,
177
+ )
178
+ field_type = list[derived]
179
+ default = [] if not sdm.is_optional else None
180
+ return field_type, default
181
+
182
+ @staticmethod
183
+ def field_names(fields, schema_type, include=None, exclude=None):
184
+ skip = set(exclude or [])
185
+ only = set(include) if include else None
186
+ return [n for n, info in fields.items()
187
+ if n not in skip and (only is None or n in only)
188
+ and info.has_config(schema_type)
189
+ and not info.get_config(schema_type).exclude]