plain 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.
- plain/README.md +33 -0
- plain/__main__.py +5 -0
- plain/assets/README.md +56 -0
- plain/assets/__init__.py +6 -0
- plain/assets/finders.py +233 -0
- plain/assets/preflight.py +14 -0
- plain/assets/storage.py +916 -0
- plain/assets/utils.py +52 -0
- plain/assets/whitenoise/__init__.py +5 -0
- plain/assets/whitenoise/base.py +259 -0
- plain/assets/whitenoise/compress.py +189 -0
- plain/assets/whitenoise/media_types.py +137 -0
- plain/assets/whitenoise/middleware.py +197 -0
- plain/assets/whitenoise/responders.py +286 -0
- plain/assets/whitenoise/storage.py +178 -0
- plain/assets/whitenoise/string_utils.py +13 -0
- plain/cli/README.md +123 -0
- plain/cli/__init__.py +3 -0
- plain/cli/cli.py +439 -0
- plain/cli/formatting.py +61 -0
- plain/cli/packages.py +73 -0
- plain/cli/print.py +9 -0
- plain/cli/startup.py +33 -0
- plain/csrf/README.md +3 -0
- plain/csrf/middleware.py +466 -0
- plain/csrf/views.py +10 -0
- plain/debug.py +23 -0
- plain/exceptions.py +242 -0
- plain/forms/README.md +14 -0
- plain/forms/__init__.py +8 -0
- plain/forms/boundfield.py +58 -0
- plain/forms/exceptions.py +11 -0
- plain/forms/fields.py +1030 -0
- plain/forms/forms.py +297 -0
- plain/http/README.md +1 -0
- plain/http/__init__.py +51 -0
- plain/http/cookie.py +20 -0
- plain/http/multipartparser.py +743 -0
- plain/http/request.py +754 -0
- plain/http/response.py +719 -0
- plain/internal/__init__.py +0 -0
- plain/internal/files/README.md +3 -0
- plain/internal/files/__init__.py +3 -0
- plain/internal/files/base.py +161 -0
- plain/internal/files/locks.py +127 -0
- plain/internal/files/move.py +102 -0
- plain/internal/files/temp.py +79 -0
- plain/internal/files/uploadedfile.py +150 -0
- plain/internal/files/uploadhandler.py +254 -0
- plain/internal/files/utils.py +78 -0
- plain/internal/handlers/__init__.py +0 -0
- plain/internal/handlers/base.py +133 -0
- plain/internal/handlers/exception.py +145 -0
- plain/internal/handlers/wsgi.py +216 -0
- plain/internal/legacy/__init__.py +0 -0
- plain/internal/legacy/__main__.py +12 -0
- plain/internal/legacy/management/__init__.py +414 -0
- plain/internal/legacy/management/base.py +692 -0
- plain/internal/legacy/management/color.py +113 -0
- plain/internal/legacy/management/commands/__init__.py +0 -0
- plain/internal/legacy/management/commands/collectstatic.py +297 -0
- plain/internal/legacy/management/sql.py +67 -0
- plain/internal/legacy/management/utils.py +175 -0
- plain/json.py +40 -0
- plain/logs/README.md +24 -0
- plain/logs/__init__.py +5 -0
- plain/logs/configure.py +39 -0
- plain/logs/loggers.py +74 -0
- plain/logs/utils.py +46 -0
- plain/middleware/README.md +3 -0
- plain/middleware/__init__.py +0 -0
- plain/middleware/clickjacking.py +52 -0
- plain/middleware/common.py +87 -0
- plain/middleware/gzip.py +64 -0
- plain/middleware/security.py +64 -0
- plain/packages/README.md +41 -0
- plain/packages/__init__.py +4 -0
- plain/packages/config.py +259 -0
- plain/packages/registry.py +438 -0
- plain/paginator.py +187 -0
- plain/preflight/README.md +3 -0
- plain/preflight/__init__.py +38 -0
- plain/preflight/compatibility/__init__.py +0 -0
- plain/preflight/compatibility/django_4_0.py +20 -0
- plain/preflight/files.py +19 -0
- plain/preflight/messages.py +88 -0
- plain/preflight/registry.py +72 -0
- plain/preflight/security/__init__.py +0 -0
- plain/preflight/security/base.py +268 -0
- plain/preflight/security/csrf.py +40 -0
- plain/preflight/urls.py +117 -0
- plain/runtime/README.md +75 -0
- plain/runtime/__init__.py +61 -0
- plain/runtime/global_settings.py +199 -0
- plain/runtime/user_settings.py +353 -0
- plain/signals/README.md +14 -0
- plain/signals/__init__.py +5 -0
- plain/signals/dispatch/__init__.py +9 -0
- plain/signals/dispatch/dispatcher.py +320 -0
- plain/signals/dispatch/license.txt +35 -0
- plain/signing.py +299 -0
- plain/templates/README.md +20 -0
- plain/templates/__init__.py +6 -0
- plain/templates/core.py +24 -0
- plain/templates/jinja/README.md +227 -0
- plain/templates/jinja/__init__.py +22 -0
- plain/templates/jinja/defaults.py +119 -0
- plain/templates/jinja/extensions.py +39 -0
- plain/templates/jinja/filters.py +28 -0
- plain/templates/jinja/globals.py +19 -0
- plain/test/README.md +3 -0
- plain/test/__init__.py +16 -0
- plain/test/client.py +985 -0
- plain/test/utils.py +255 -0
- plain/urls/README.md +3 -0
- plain/urls/__init__.py +40 -0
- plain/urls/base.py +118 -0
- plain/urls/conf.py +94 -0
- plain/urls/converters.py +66 -0
- plain/urls/exceptions.py +9 -0
- plain/urls/resolvers.py +731 -0
- plain/utils/README.md +3 -0
- plain/utils/__init__.py +0 -0
- plain/utils/_os.py +52 -0
- plain/utils/cache.py +327 -0
- plain/utils/connection.py +84 -0
- plain/utils/crypto.py +76 -0
- plain/utils/datastructures.py +345 -0
- plain/utils/dateformat.py +329 -0
- plain/utils/dateparse.py +154 -0
- plain/utils/dates.py +76 -0
- plain/utils/deconstruct.py +54 -0
- plain/utils/decorators.py +90 -0
- plain/utils/deprecation.py +6 -0
- plain/utils/duration.py +44 -0
- plain/utils/email.py +12 -0
- plain/utils/encoding.py +235 -0
- plain/utils/functional.py +456 -0
- plain/utils/hashable.py +26 -0
- plain/utils/html.py +401 -0
- plain/utils/http.py +374 -0
- plain/utils/inspect.py +73 -0
- plain/utils/ipv6.py +46 -0
- plain/utils/itercompat.py +8 -0
- plain/utils/module_loading.py +69 -0
- plain/utils/regex_helper.py +353 -0
- plain/utils/safestring.py +72 -0
- plain/utils/termcolors.py +221 -0
- plain/utils/text.py +518 -0
- plain/utils/timesince.py +138 -0
- plain/utils/timezone.py +244 -0
- plain/utils/tree.py +126 -0
- plain/validators.py +603 -0
- plain/views/README.md +268 -0
- plain/views/__init__.py +18 -0
- plain/views/base.py +107 -0
- plain/views/csrf.py +24 -0
- plain/views/errors.py +25 -0
- plain/views/exceptions.py +4 -0
- plain/views/forms.py +76 -0
- plain/views/objects.py +229 -0
- plain/views/redirect.py +72 -0
- plain/views/templates.py +66 -0
- plain/wsgi.py +11 -0
- plain-0.1.0.dist-info/LICENSE +85 -0
- plain-0.1.0.dist-info/METADATA +51 -0
- plain-0.1.0.dist-info/RECORD +169 -0
- plain-0.1.0.dist-info/WHEEL +4 -0
- plain-0.1.0.dist-info/entry_points.txt +3 -0
plain/packages/config.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import inspect
|
|
2
|
+
import os
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
|
|
5
|
+
from plain.exceptions import ImproperlyConfigured
|
|
6
|
+
from plain.utils.module_loading import import_string, module_has_submodule
|
|
7
|
+
|
|
8
|
+
CONFIG_MODULE_NAME = "config"
|
|
9
|
+
MODELS_MODULE_NAME = "models"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PackageConfig:
|
|
13
|
+
"""Class representing a Plain application and its configuration."""
|
|
14
|
+
|
|
15
|
+
migrations_module = "migrations"
|
|
16
|
+
|
|
17
|
+
def __init__(self, package_name, package_module):
|
|
18
|
+
# Full Python path to the application e.g. 'plain.staff.admin.admin'.
|
|
19
|
+
self.name = package_name
|
|
20
|
+
|
|
21
|
+
# Root module for the application e.g. <module 'plain.staff.admin.admin'
|
|
22
|
+
# from 'admin/__init__.py'>.
|
|
23
|
+
self.module = package_module
|
|
24
|
+
|
|
25
|
+
# Reference to the Packages registry that holds this PackageConfig. Set by the
|
|
26
|
+
# registry when it registers the PackageConfig instance.
|
|
27
|
+
self.packages = None
|
|
28
|
+
|
|
29
|
+
# The following attributes could be defined at the class level in a
|
|
30
|
+
# subclass, hence the test-and-set pattern.
|
|
31
|
+
|
|
32
|
+
# Last component of the Python path to the application e.g. 'admin'.
|
|
33
|
+
# This value must be unique across a Plain project.
|
|
34
|
+
if not hasattr(self, "label"):
|
|
35
|
+
self.label = package_name.rpartition(".")[2]
|
|
36
|
+
if not self.label.isidentifier():
|
|
37
|
+
raise ImproperlyConfigured(
|
|
38
|
+
"The app label '%s' is not a valid Python identifier." % self.label
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Filesystem path to the application directory e.g.
|
|
42
|
+
# '/path/to/admin'.
|
|
43
|
+
if not hasattr(self, "path"):
|
|
44
|
+
self.path = self._path_from_module(package_module)
|
|
45
|
+
|
|
46
|
+
# Module containing models e.g. <module 'plain.staff.admin.models'
|
|
47
|
+
# from 'admin/models.py'>. Set by import_models().
|
|
48
|
+
# None if the application doesn't have a models module.
|
|
49
|
+
self.models_module = None
|
|
50
|
+
|
|
51
|
+
# Mapping of lowercase model names to model classes. Initially set to
|
|
52
|
+
# None to prevent accidental access before import_models() runs.
|
|
53
|
+
self.models = None
|
|
54
|
+
|
|
55
|
+
def __repr__(self):
|
|
56
|
+
return f"<{self.__class__.__name__}: {self.label}>"
|
|
57
|
+
|
|
58
|
+
def _path_from_module(self, module):
|
|
59
|
+
"""Attempt to determine app's filesystem path from its module."""
|
|
60
|
+
# See #21874 for extended discussion of the behavior of this method in
|
|
61
|
+
# various cases.
|
|
62
|
+
# Convert to list because __path__ may not support indexing.
|
|
63
|
+
paths = list(getattr(module, "__path__", []))
|
|
64
|
+
if len(paths) != 1:
|
|
65
|
+
filename = getattr(module, "__file__", None)
|
|
66
|
+
if filename is not None:
|
|
67
|
+
paths = [os.path.dirname(filename)]
|
|
68
|
+
else:
|
|
69
|
+
# For unknown reasons, sometimes the list returned by __path__
|
|
70
|
+
# contains duplicates that must be removed (#25246).
|
|
71
|
+
paths = list(set(paths))
|
|
72
|
+
if len(paths) > 1:
|
|
73
|
+
raise ImproperlyConfigured(
|
|
74
|
+
"The app module {!r} has multiple filesystem locations ({!r}); "
|
|
75
|
+
"you must configure this app with an PackageConfig subclass "
|
|
76
|
+
"with a 'path' class attribute.".format(module, paths)
|
|
77
|
+
)
|
|
78
|
+
elif not paths:
|
|
79
|
+
raise ImproperlyConfigured(
|
|
80
|
+
"The app module %r has no filesystem location, "
|
|
81
|
+
"you must configure this app with an PackageConfig subclass "
|
|
82
|
+
"with a 'path' class attribute." % module
|
|
83
|
+
)
|
|
84
|
+
return paths[0]
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def create(cls, entry):
|
|
88
|
+
"""
|
|
89
|
+
Factory that creates an app config from an entry in INSTALLED_PACKAGES.
|
|
90
|
+
"""
|
|
91
|
+
# create() eventually returns package_config_class(package_name, package_module).
|
|
92
|
+
package_config_class = None
|
|
93
|
+
package_name = None
|
|
94
|
+
package_module = None
|
|
95
|
+
|
|
96
|
+
# If import_module succeeds, entry points to the app module.
|
|
97
|
+
try:
|
|
98
|
+
package_module = import_module(entry)
|
|
99
|
+
except Exception:
|
|
100
|
+
pass
|
|
101
|
+
else:
|
|
102
|
+
# If package_module has an packages submodule that defines a single
|
|
103
|
+
# PackageConfig subclass, use it automatically.
|
|
104
|
+
# To prevent this, an PackageConfig subclass can declare a class
|
|
105
|
+
# variable default = False.
|
|
106
|
+
# If the packages module defines more than one PackageConfig subclass,
|
|
107
|
+
# the default one can declare default = True.
|
|
108
|
+
if module_has_submodule(package_module, CONFIG_MODULE_NAME):
|
|
109
|
+
mod_path = f"{entry}.{CONFIG_MODULE_NAME}"
|
|
110
|
+
mod = import_module(mod_path)
|
|
111
|
+
# Check if there's exactly one PackageConfig candidate,
|
|
112
|
+
# excluding those that explicitly define default = False.
|
|
113
|
+
package_configs = [
|
|
114
|
+
(name, candidate)
|
|
115
|
+
for name, candidate in inspect.getmembers(mod, inspect.isclass)
|
|
116
|
+
if (
|
|
117
|
+
issubclass(candidate, cls)
|
|
118
|
+
and candidate is not cls
|
|
119
|
+
and getattr(candidate, "default", True)
|
|
120
|
+
)
|
|
121
|
+
]
|
|
122
|
+
if len(package_configs) == 1:
|
|
123
|
+
package_config_class = package_configs[0][1]
|
|
124
|
+
else:
|
|
125
|
+
# Check if there's exactly one PackageConfig subclass,
|
|
126
|
+
# among those that explicitly define default = True.
|
|
127
|
+
package_configs = [
|
|
128
|
+
(name, candidate)
|
|
129
|
+
for name, candidate in package_configs
|
|
130
|
+
if getattr(candidate, "default", False)
|
|
131
|
+
]
|
|
132
|
+
if len(package_configs) > 1:
|
|
133
|
+
candidates = [repr(name) for name, _ in package_configs]
|
|
134
|
+
raise RuntimeError(
|
|
135
|
+
"{!r} declares more than one default PackageConfig: "
|
|
136
|
+
"{}.".format(mod_path, ", ".join(candidates))
|
|
137
|
+
)
|
|
138
|
+
elif len(package_configs) == 1:
|
|
139
|
+
package_config_class = package_configs[0][1]
|
|
140
|
+
|
|
141
|
+
# Use the default app config class if we didn't find anything.
|
|
142
|
+
if package_config_class is None:
|
|
143
|
+
package_config_class = cls
|
|
144
|
+
package_name = entry
|
|
145
|
+
|
|
146
|
+
# If import_string succeeds, entry is an app config class.
|
|
147
|
+
if package_config_class is None:
|
|
148
|
+
try:
|
|
149
|
+
package_config_class = import_string(entry)
|
|
150
|
+
except Exception:
|
|
151
|
+
pass
|
|
152
|
+
# If both import_module and import_string failed, it means that entry
|
|
153
|
+
# doesn't have a valid value.
|
|
154
|
+
if package_module is None and package_config_class is None:
|
|
155
|
+
# If the last component of entry starts with an uppercase letter,
|
|
156
|
+
# then it was likely intended to be an app config class; if not,
|
|
157
|
+
# an app module. Provide a nice error message in both cases.
|
|
158
|
+
mod_path, _, cls_name = entry.rpartition(".")
|
|
159
|
+
if mod_path and cls_name[0].isupper():
|
|
160
|
+
# We could simply re-trigger the string import exception, but
|
|
161
|
+
# we're going the extra mile and providing a better error
|
|
162
|
+
# message for typos in INSTALLED_PACKAGES.
|
|
163
|
+
# This may raise ImportError, which is the best exception
|
|
164
|
+
# possible if the module at mod_path cannot be imported.
|
|
165
|
+
mod = import_module(mod_path)
|
|
166
|
+
candidates = [
|
|
167
|
+
repr(name)
|
|
168
|
+
for name, candidate in inspect.getmembers(mod, inspect.isclass)
|
|
169
|
+
if issubclass(candidate, cls) and candidate is not cls
|
|
170
|
+
]
|
|
171
|
+
msg = f"Module '{mod_path}' does not contain a '{cls_name}' class."
|
|
172
|
+
if candidates:
|
|
173
|
+
msg += " Choices are: %s." % ", ".join(candidates)
|
|
174
|
+
raise ImportError(msg)
|
|
175
|
+
else:
|
|
176
|
+
# Re-trigger the module import exception.
|
|
177
|
+
import_module(entry)
|
|
178
|
+
|
|
179
|
+
# Check for obvious errors. (This check prevents duck typing, but
|
|
180
|
+
# it could be removed if it became a problem in practice.)
|
|
181
|
+
if not issubclass(package_config_class, PackageConfig):
|
|
182
|
+
raise ImproperlyConfigured(
|
|
183
|
+
"'%s' isn't a subclass of PackageConfig." % entry
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
# Obtain package name here rather than in PackageClass.__init__ to keep
|
|
187
|
+
# all error checking for entries in INSTALLED_PACKAGES in one place.
|
|
188
|
+
if package_name is None:
|
|
189
|
+
try:
|
|
190
|
+
package_name = package_config_class.name
|
|
191
|
+
except AttributeError:
|
|
192
|
+
raise ImproperlyConfigured("'%s' must supply a name attribute." % entry)
|
|
193
|
+
|
|
194
|
+
# Ensure package_name points to a valid module.
|
|
195
|
+
try:
|
|
196
|
+
package_module = import_module(package_name)
|
|
197
|
+
except ImportError:
|
|
198
|
+
raise ImproperlyConfigured(
|
|
199
|
+
"Cannot import '{}'. Check that '{}.{}.name' is correct.".format(
|
|
200
|
+
package_name,
|
|
201
|
+
package_config_class.__module__,
|
|
202
|
+
package_config_class.__qualname__,
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
# Entry is a path to an app config class.
|
|
207
|
+
return package_config_class(package_name, package_module)
|
|
208
|
+
|
|
209
|
+
def get_model(self, model_name, require_ready=True):
|
|
210
|
+
"""
|
|
211
|
+
Return the model with the given case-insensitive model_name.
|
|
212
|
+
|
|
213
|
+
Raise LookupError if no model exists with this name.
|
|
214
|
+
"""
|
|
215
|
+
if require_ready:
|
|
216
|
+
self.packages.check_models_ready()
|
|
217
|
+
else:
|
|
218
|
+
self.packages.check_packages_ready()
|
|
219
|
+
try:
|
|
220
|
+
return self.models[model_name.lower()]
|
|
221
|
+
except KeyError:
|
|
222
|
+
raise LookupError(
|
|
223
|
+
f"Package '{self.label}' doesn't have a '{model_name}' model."
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
def get_models(self, include_auto_created=False, include_swapped=False):
|
|
227
|
+
"""
|
|
228
|
+
Return an iterable of models.
|
|
229
|
+
|
|
230
|
+
By default, the following models aren't included:
|
|
231
|
+
|
|
232
|
+
- auto-created models for many-to-many relations without
|
|
233
|
+
an explicit intermediate table,
|
|
234
|
+
- models that have been swapped out.
|
|
235
|
+
|
|
236
|
+
Set the corresponding keyword argument to True to include such models.
|
|
237
|
+
Keyword arguments aren't documented; they're a private API.
|
|
238
|
+
"""
|
|
239
|
+
self.packages.check_models_ready()
|
|
240
|
+
for model in self.models.values():
|
|
241
|
+
if model._meta.auto_created and not include_auto_created:
|
|
242
|
+
continue
|
|
243
|
+
if model._meta.swapped and not include_swapped:
|
|
244
|
+
continue
|
|
245
|
+
yield model
|
|
246
|
+
|
|
247
|
+
def import_models(self):
|
|
248
|
+
# Dictionary of models for this app, primarily maintained in the
|
|
249
|
+
# 'all_models' attribute of the Packages this PackageConfig is attached to.
|
|
250
|
+
self.models = self.packages.all_models[self.label]
|
|
251
|
+
|
|
252
|
+
if module_has_submodule(self.module, MODELS_MODULE_NAME):
|
|
253
|
+
models_module_name = f"{self.name}.{MODELS_MODULE_NAME}"
|
|
254
|
+
self.models_module = import_module(models_module_name)
|
|
255
|
+
|
|
256
|
+
def ready(self):
|
|
257
|
+
"""
|
|
258
|
+
Override this method in subclasses to run code when Plain starts.
|
|
259
|
+
"""
|
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
import sys
|
|
3
|
+
import threading
|
|
4
|
+
import warnings
|
|
5
|
+
from collections import Counter, defaultdict
|
|
6
|
+
from functools import partial
|
|
7
|
+
|
|
8
|
+
from plain.exceptions import ImproperlyConfigured, PackageRegistryNotReady
|
|
9
|
+
|
|
10
|
+
from .config import PackageConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Packages:
|
|
14
|
+
"""
|
|
15
|
+
A registry that stores the configuration of installed applications.
|
|
16
|
+
|
|
17
|
+
It also keeps track of models, e.g. to provide reverse relations.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(self, installed_packages=()):
|
|
21
|
+
# installed_packages is set to None when creating the main registry
|
|
22
|
+
# because it cannot be populated at that point. Other registries must
|
|
23
|
+
# provide a list of installed packages and are populated immediately.
|
|
24
|
+
if installed_packages is None and hasattr(sys.modules[__name__], "packages"):
|
|
25
|
+
raise RuntimeError("You must supply an installed_packages argument.")
|
|
26
|
+
|
|
27
|
+
# Mapping of app labels => model names => model classes. Every time a
|
|
28
|
+
# model is imported, ModelBase.__new__ calls packages.register_model which
|
|
29
|
+
# creates an entry in all_models. All imported models are registered,
|
|
30
|
+
# regardless of whether they're defined in an installed application
|
|
31
|
+
# and whether the registry has been populated. Since it isn't possible
|
|
32
|
+
# to reimport a module safely (it could reexecute initialization code)
|
|
33
|
+
# all_models is never overridden or reset.
|
|
34
|
+
self.all_models = defaultdict(dict)
|
|
35
|
+
|
|
36
|
+
# Mapping of labels to PackageConfig instances for installed packages.
|
|
37
|
+
self.package_configs = {}
|
|
38
|
+
|
|
39
|
+
# Stack of package_configs. Used to store the current state in
|
|
40
|
+
# set_available_packages and set_installed_packages.
|
|
41
|
+
self.stored_package_configs = []
|
|
42
|
+
|
|
43
|
+
# Whether the registry is populated.
|
|
44
|
+
self.packages_ready = self.models_ready = self.ready = False
|
|
45
|
+
|
|
46
|
+
# Lock for thread-safe population.
|
|
47
|
+
self._lock = threading.RLock()
|
|
48
|
+
self.loading = False
|
|
49
|
+
|
|
50
|
+
# Maps ("package_label", "modelname") tuples to lists of functions to be
|
|
51
|
+
# called when the corresponding model is ready. Used by this class's
|
|
52
|
+
# `lazy_model_operation()` and `do_pending_operations()` methods.
|
|
53
|
+
self._pending_operations = defaultdict(list)
|
|
54
|
+
|
|
55
|
+
# Populate packages and models, unless it's the main registry.
|
|
56
|
+
if installed_packages is not None:
|
|
57
|
+
self.populate(installed_packages)
|
|
58
|
+
|
|
59
|
+
def populate(self, installed_packages=None):
|
|
60
|
+
"""
|
|
61
|
+
Load application configurations and models.
|
|
62
|
+
|
|
63
|
+
Import each application module and then each model module.
|
|
64
|
+
|
|
65
|
+
It is thread-safe and idempotent, but not reentrant.
|
|
66
|
+
"""
|
|
67
|
+
if self.ready:
|
|
68
|
+
return
|
|
69
|
+
|
|
70
|
+
# populate() might be called by two threads in parallel on servers
|
|
71
|
+
# that create threads before initializing the WSGI callable.
|
|
72
|
+
with self._lock:
|
|
73
|
+
if self.ready:
|
|
74
|
+
return
|
|
75
|
+
|
|
76
|
+
# An RLock prevents other threads from entering this section. The
|
|
77
|
+
# compare and set operation below is atomic.
|
|
78
|
+
if self.loading:
|
|
79
|
+
# Prevent reentrant calls to avoid running PackageConfig.ready()
|
|
80
|
+
# methods twice.
|
|
81
|
+
raise RuntimeError("populate() isn't reentrant")
|
|
82
|
+
self.loading = True
|
|
83
|
+
|
|
84
|
+
# Phase 1: initialize app configs and import app modules.
|
|
85
|
+
for entry in installed_packages:
|
|
86
|
+
if isinstance(entry, PackageConfig):
|
|
87
|
+
package_config = entry
|
|
88
|
+
else:
|
|
89
|
+
package_config = PackageConfig.create(entry)
|
|
90
|
+
if package_config.label in self.package_configs:
|
|
91
|
+
raise ImproperlyConfigured(
|
|
92
|
+
"Package labels aren't unique, "
|
|
93
|
+
"duplicates: %s" % package_config.label
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
self.package_configs[package_config.label] = package_config
|
|
97
|
+
package_config.packages = self
|
|
98
|
+
|
|
99
|
+
# Check for duplicate app names.
|
|
100
|
+
counts = Counter(
|
|
101
|
+
package_config.name for package_config in self.package_configs.values()
|
|
102
|
+
)
|
|
103
|
+
duplicates = [name for name, count in counts.most_common() if count > 1]
|
|
104
|
+
if duplicates:
|
|
105
|
+
raise ImproperlyConfigured(
|
|
106
|
+
"Package names aren't unique, "
|
|
107
|
+
"duplicates: %s" % ", ".join(duplicates)
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
self.packages_ready = True
|
|
111
|
+
|
|
112
|
+
# Phase 2: import models modules.
|
|
113
|
+
for package_config in self.package_configs.values():
|
|
114
|
+
package_config.import_models()
|
|
115
|
+
|
|
116
|
+
self.clear_cache()
|
|
117
|
+
|
|
118
|
+
self.models_ready = True
|
|
119
|
+
|
|
120
|
+
# Phase 3: run ready() methods of app configs.
|
|
121
|
+
for package_config in self.get_package_configs():
|
|
122
|
+
package_config.ready()
|
|
123
|
+
|
|
124
|
+
self.ready = True
|
|
125
|
+
|
|
126
|
+
def check_packages_ready(self):
|
|
127
|
+
"""Raise an exception if all packages haven't been imported yet."""
|
|
128
|
+
if not self.packages_ready:
|
|
129
|
+
from plain.runtime import settings
|
|
130
|
+
|
|
131
|
+
# If "not ready" is due to unconfigured settings, accessing
|
|
132
|
+
# INSTALLED_PACKAGES raises a more helpful ImproperlyConfigured
|
|
133
|
+
# exception.
|
|
134
|
+
settings.INSTALLED_PACKAGES
|
|
135
|
+
raise PackageRegistryNotReady("Packages aren't loaded yet.")
|
|
136
|
+
|
|
137
|
+
def check_models_ready(self):
|
|
138
|
+
"""Raise an exception if all models haven't been imported yet."""
|
|
139
|
+
if not self.models_ready:
|
|
140
|
+
raise PackageRegistryNotReady("Models aren't loaded yet.")
|
|
141
|
+
|
|
142
|
+
def get_package_configs(self):
|
|
143
|
+
"""Import applications and return an iterable of app configs."""
|
|
144
|
+
self.check_packages_ready()
|
|
145
|
+
return self.package_configs.values()
|
|
146
|
+
|
|
147
|
+
def get_package_config(self, package_label):
|
|
148
|
+
"""
|
|
149
|
+
Import applications and returns an app config for the given label.
|
|
150
|
+
|
|
151
|
+
Raise LookupError if no application exists with this label.
|
|
152
|
+
"""
|
|
153
|
+
self.check_packages_ready()
|
|
154
|
+
try:
|
|
155
|
+
return self.package_configs[package_label]
|
|
156
|
+
except KeyError:
|
|
157
|
+
message = "No installed app with label '%s'." % package_label
|
|
158
|
+
for package_config in self.get_package_configs():
|
|
159
|
+
if package_config.name == package_label:
|
|
160
|
+
message += " Did you mean '%s'?" % package_config.label
|
|
161
|
+
break
|
|
162
|
+
raise LookupError(message)
|
|
163
|
+
|
|
164
|
+
# This method is performance-critical at least for Plain's test suite.
|
|
165
|
+
@functools.cache
|
|
166
|
+
def get_models(self, include_auto_created=False, include_swapped=False):
|
|
167
|
+
"""
|
|
168
|
+
Return a list of all installed models.
|
|
169
|
+
|
|
170
|
+
By default, the following models aren't included:
|
|
171
|
+
|
|
172
|
+
- auto-created models for many-to-many relations without
|
|
173
|
+
an explicit intermediate table,
|
|
174
|
+
- models that have been swapped out.
|
|
175
|
+
|
|
176
|
+
Set the corresponding keyword argument to True to include such models.
|
|
177
|
+
"""
|
|
178
|
+
self.check_models_ready()
|
|
179
|
+
|
|
180
|
+
result = []
|
|
181
|
+
for package_config in self.package_configs.values():
|
|
182
|
+
result.extend(
|
|
183
|
+
package_config.get_models(include_auto_created, include_swapped)
|
|
184
|
+
)
|
|
185
|
+
return result
|
|
186
|
+
|
|
187
|
+
def get_model(self, package_label, model_name=None, require_ready=True):
|
|
188
|
+
"""
|
|
189
|
+
Return the model matching the given package_label and model_name.
|
|
190
|
+
|
|
191
|
+
As a shortcut, package_label may be in the form <package_label>.<model_name>.
|
|
192
|
+
|
|
193
|
+
model_name is case-insensitive.
|
|
194
|
+
|
|
195
|
+
Raise LookupError if no application exists with this label, or no
|
|
196
|
+
model exists with this name in the application. Raise ValueError if
|
|
197
|
+
called with a single argument that doesn't contain exactly one dot.
|
|
198
|
+
"""
|
|
199
|
+
if require_ready:
|
|
200
|
+
self.check_models_ready()
|
|
201
|
+
else:
|
|
202
|
+
self.check_packages_ready()
|
|
203
|
+
|
|
204
|
+
if model_name is None:
|
|
205
|
+
package_label, model_name = package_label.split(".")
|
|
206
|
+
|
|
207
|
+
package_config = self.get_package_config(package_label)
|
|
208
|
+
|
|
209
|
+
if not require_ready and package_config.models is None:
|
|
210
|
+
package_config.import_models()
|
|
211
|
+
|
|
212
|
+
return package_config.get_model(model_name, require_ready=require_ready)
|
|
213
|
+
|
|
214
|
+
def register_model(self, package_label, model):
|
|
215
|
+
# Since this method is called when models are imported, it cannot
|
|
216
|
+
# perform imports because of the risk of import loops. It mustn't
|
|
217
|
+
# call get_package_config().
|
|
218
|
+
model_name = model._meta.model_name
|
|
219
|
+
app_models = self.all_models[package_label]
|
|
220
|
+
if model_name in app_models:
|
|
221
|
+
if (
|
|
222
|
+
model.__name__ == app_models[model_name].__name__
|
|
223
|
+
and model.__module__ == app_models[model_name].__module__
|
|
224
|
+
):
|
|
225
|
+
warnings.warn(
|
|
226
|
+
"Model '{}.{}' was already registered. Reloading models is not "
|
|
227
|
+
"advised as it can lead to inconsistencies, most notably with "
|
|
228
|
+
"related models.".format(package_label, model_name),
|
|
229
|
+
RuntimeWarning,
|
|
230
|
+
stacklevel=2,
|
|
231
|
+
)
|
|
232
|
+
else:
|
|
233
|
+
raise RuntimeError(
|
|
234
|
+
"Conflicting '{}' models in application '{}': {} and {}.".format(
|
|
235
|
+
model_name, package_label, app_models[model_name], model
|
|
236
|
+
)
|
|
237
|
+
)
|
|
238
|
+
app_models[model_name] = model
|
|
239
|
+
self.do_pending_operations(model)
|
|
240
|
+
self.clear_cache()
|
|
241
|
+
|
|
242
|
+
def is_installed(self, package_name):
|
|
243
|
+
"""
|
|
244
|
+
Check whether an application with this name exists in the registry.
|
|
245
|
+
|
|
246
|
+
package_name is the full name of the app e.g. 'plain.staff.admin'.
|
|
247
|
+
"""
|
|
248
|
+
self.check_packages_ready()
|
|
249
|
+
return any(ac.name == package_name for ac in self.package_configs.values())
|
|
250
|
+
|
|
251
|
+
def get_containing_package_config(self, object_name):
|
|
252
|
+
"""
|
|
253
|
+
Look for an app config containing a given object.
|
|
254
|
+
|
|
255
|
+
object_name is the dotted Python path to the object.
|
|
256
|
+
|
|
257
|
+
Return the app config for the inner application in case of nesting.
|
|
258
|
+
Return None if the object isn't in any registered app config.
|
|
259
|
+
"""
|
|
260
|
+
self.check_packages_ready()
|
|
261
|
+
candidates = []
|
|
262
|
+
for package_config in self.package_configs.values():
|
|
263
|
+
if object_name.startswith(package_config.name):
|
|
264
|
+
subpath = object_name.removeprefix(package_config.name)
|
|
265
|
+
if subpath == "" or subpath[0] == ".":
|
|
266
|
+
candidates.append(package_config)
|
|
267
|
+
if candidates:
|
|
268
|
+
return sorted(candidates, key=lambda ac: -len(ac.name))[0]
|
|
269
|
+
|
|
270
|
+
def get_registered_model(self, package_label, model_name):
|
|
271
|
+
"""
|
|
272
|
+
Similar to get_model(), but doesn't require that an app exists with
|
|
273
|
+
the given package_label.
|
|
274
|
+
|
|
275
|
+
It's safe to call this method at import time, even while the registry
|
|
276
|
+
is being populated.
|
|
277
|
+
"""
|
|
278
|
+
model = self.all_models[package_label].get(model_name.lower())
|
|
279
|
+
if model is None:
|
|
280
|
+
raise LookupError(f"Model '{package_label}.{model_name}' not registered.")
|
|
281
|
+
return model
|
|
282
|
+
|
|
283
|
+
@functools.cache
|
|
284
|
+
def get_swappable_settings_name(self, to_string):
|
|
285
|
+
"""
|
|
286
|
+
For a given model string (e.g. "auth.User"), return the name of the
|
|
287
|
+
corresponding settings name if it refers to a swappable model. If the
|
|
288
|
+
referred model is not swappable, return None.
|
|
289
|
+
|
|
290
|
+
This method is decorated with @functools.cache because it's performance
|
|
291
|
+
critical when it comes to migrations. Since the swappable settings don't
|
|
292
|
+
change after Plain has loaded the settings, there is no reason to get
|
|
293
|
+
the respective settings attribute over and over again.
|
|
294
|
+
"""
|
|
295
|
+
to_string = to_string.lower()
|
|
296
|
+
for model in self.get_models(include_swapped=True):
|
|
297
|
+
swapped = model._meta.swapped
|
|
298
|
+
# Is this model swapped out for the model given by to_string?
|
|
299
|
+
if swapped and swapped.lower() == to_string:
|
|
300
|
+
return model._meta.swappable
|
|
301
|
+
# Is this model swappable and the one given by to_string?
|
|
302
|
+
if model._meta.swappable and model._meta.label_lower == to_string:
|
|
303
|
+
return model._meta.swappable
|
|
304
|
+
return None
|
|
305
|
+
|
|
306
|
+
def set_available_packages(self, available):
|
|
307
|
+
"""
|
|
308
|
+
Restrict the set of installed packages used by get_package_config[s].
|
|
309
|
+
|
|
310
|
+
available must be an iterable of application names.
|
|
311
|
+
|
|
312
|
+
set_available_packages() must be balanced with unset_available_packages().
|
|
313
|
+
|
|
314
|
+
Primarily used for performance optimization in TransactionTestCase.
|
|
315
|
+
|
|
316
|
+
This method is safe in the sense that it doesn't trigger any imports.
|
|
317
|
+
"""
|
|
318
|
+
available = set(available)
|
|
319
|
+
installed = {
|
|
320
|
+
package_config.name for package_config in self.get_package_configs()
|
|
321
|
+
}
|
|
322
|
+
if not available.issubset(installed):
|
|
323
|
+
raise ValueError(
|
|
324
|
+
"Available packages isn't a subset of installed packages, extra packages: %s"
|
|
325
|
+
% ", ".join(available - installed)
|
|
326
|
+
)
|
|
327
|
+
|
|
328
|
+
self.stored_package_configs.append(self.package_configs)
|
|
329
|
+
self.package_configs = {
|
|
330
|
+
label: package_config
|
|
331
|
+
for label, package_config in self.package_configs.items()
|
|
332
|
+
if package_config.name in available
|
|
333
|
+
}
|
|
334
|
+
self.clear_cache()
|
|
335
|
+
|
|
336
|
+
def unset_available_packages(self):
|
|
337
|
+
"""Cancel a previous call to set_available_packages()."""
|
|
338
|
+
self.package_configs = self.stored_package_configs.pop()
|
|
339
|
+
self.clear_cache()
|
|
340
|
+
|
|
341
|
+
def set_installed_packages(self, installed):
|
|
342
|
+
"""
|
|
343
|
+
Enable a different set of installed packages for get_package_config[s].
|
|
344
|
+
|
|
345
|
+
installed must be an iterable in the same format as INSTALLED_PACKAGES.
|
|
346
|
+
|
|
347
|
+
set_installed_packages() must be balanced with unset_installed_packages(),
|
|
348
|
+
even if it exits with an exception.
|
|
349
|
+
|
|
350
|
+
Primarily used as a receiver of the setting_changed signal in tests.
|
|
351
|
+
|
|
352
|
+
This method may trigger new imports, which may add new models to the
|
|
353
|
+
registry of all imported models. They will stay in the registry even
|
|
354
|
+
after unset_installed_packages(). Since it isn't possible to replay
|
|
355
|
+
imports safely (e.g. that could lead to registering listeners twice),
|
|
356
|
+
models are registered when they're imported and never removed.
|
|
357
|
+
"""
|
|
358
|
+
if not self.ready:
|
|
359
|
+
raise PackageRegistryNotReady("Package registry isn't ready yet.")
|
|
360
|
+
self.stored_package_configs.append(self.package_configs)
|
|
361
|
+
self.package_configs = {}
|
|
362
|
+
self.packages_ready = self.models_ready = self.loading = self.ready = False
|
|
363
|
+
self.clear_cache()
|
|
364
|
+
self.populate(installed)
|
|
365
|
+
|
|
366
|
+
def unset_installed_packages(self):
|
|
367
|
+
"""Cancel a previous call to set_installed_packages()."""
|
|
368
|
+
self.package_configs = self.stored_package_configs.pop()
|
|
369
|
+
self.packages_ready = self.models_ready = self.ready = True
|
|
370
|
+
self.clear_cache()
|
|
371
|
+
|
|
372
|
+
def clear_cache(self):
|
|
373
|
+
"""
|
|
374
|
+
Clear all internal caches, for methods that alter the app registry.
|
|
375
|
+
|
|
376
|
+
This is mostly used in tests.
|
|
377
|
+
"""
|
|
378
|
+
# Call expire cache on each model. This will purge
|
|
379
|
+
# the relation tree and the fields cache.
|
|
380
|
+
self.get_models.cache_clear()
|
|
381
|
+
if self.ready:
|
|
382
|
+
# Circumvent self.get_models() to prevent that the cache is refilled.
|
|
383
|
+
# This particularly prevents that an empty value is cached while cloning.
|
|
384
|
+
for package_config in self.package_configs.values():
|
|
385
|
+
for model in package_config.get_models(include_auto_created=True):
|
|
386
|
+
model._meta._expire_cache()
|
|
387
|
+
|
|
388
|
+
def lazy_model_operation(self, function, *model_keys):
|
|
389
|
+
"""
|
|
390
|
+
Take a function and a number of ("package_label", "modelname") tuples, and
|
|
391
|
+
when all the corresponding models have been imported and registered,
|
|
392
|
+
call the function with the model classes as its arguments.
|
|
393
|
+
|
|
394
|
+
The function passed to this method must accept exactly n models as
|
|
395
|
+
arguments, where n=len(model_keys).
|
|
396
|
+
"""
|
|
397
|
+
# Base case: no arguments, just execute the function.
|
|
398
|
+
if not model_keys:
|
|
399
|
+
function()
|
|
400
|
+
# Recursive case: take the head of model_keys, wait for the
|
|
401
|
+
# corresponding model class to be imported and registered, then apply
|
|
402
|
+
# that argument to the supplied function. Pass the resulting partial
|
|
403
|
+
# to lazy_model_operation() along with the remaining model args and
|
|
404
|
+
# repeat until all models are loaded and all arguments are applied.
|
|
405
|
+
else:
|
|
406
|
+
next_model, *more_models = model_keys
|
|
407
|
+
|
|
408
|
+
# This will be executed after the class corresponding to next_model
|
|
409
|
+
# has been imported and registered. The `func` attribute provides
|
|
410
|
+
# duck-type compatibility with partials.
|
|
411
|
+
def apply_next_model(model):
|
|
412
|
+
next_function = partial(apply_next_model.func, model)
|
|
413
|
+
self.lazy_model_operation(next_function, *more_models)
|
|
414
|
+
|
|
415
|
+
apply_next_model.func = function
|
|
416
|
+
|
|
417
|
+
# If the model has already been imported and registered, partially
|
|
418
|
+
# apply it to the function now. If not, add it to the list of
|
|
419
|
+
# pending operations for the model, where it will be executed with
|
|
420
|
+
# the model class as its sole argument once the model is ready.
|
|
421
|
+
try:
|
|
422
|
+
model_class = self.get_registered_model(*next_model)
|
|
423
|
+
except LookupError:
|
|
424
|
+
self._pending_operations[next_model].append(apply_next_model)
|
|
425
|
+
else:
|
|
426
|
+
apply_next_model(model_class)
|
|
427
|
+
|
|
428
|
+
def do_pending_operations(self, model):
|
|
429
|
+
"""
|
|
430
|
+
Take a newly-prepared model and pass it to each function waiting for
|
|
431
|
+
it. This is called at the very end of Packages.register_model().
|
|
432
|
+
"""
|
|
433
|
+
key = model._meta.package_label, model._meta.model_name
|
|
434
|
+
for function in self._pending_operations.pop(key, []):
|
|
435
|
+
function(model)
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
packages = Packages(installed_packages=None)
|