plain 0.26.0__py3-none-any.whl → 0.27.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.
@@ -1,9 +1,6 @@
1
- import functools
2
1
  import sys
3
2
  import threading
4
- import warnings
5
- from collections import Counter, defaultdict
6
- from functools import partial
3
+ from collections import Counter
7
4
  from importlib import import_module
8
5
 
9
6
  from plain.exceptions import ImproperlyConfigured, PackageRegistryNotReady
@@ -29,30 +26,16 @@ class PackagesRegistry:
29
26
  ):
30
27
  raise RuntimeError("You must supply an installed_packages argument.")
31
28
 
32
- # Mapping of app labels => model names => model classes.
33
- # Models are registered with @models.register_model, which
34
- # creates an entry in all_models. All imported models are registered,
35
- # regardless of whether they're defined in an installed application
36
- # and whether the registry has been populated. Since it isn't possible
37
- # to reimport a module safely (it could reexecute initialization code)
38
- # all_models is never overridden or reset.
39
- self.all_models = defaultdict(dict)
40
-
41
29
  # Mapping of labels to PackageConfig instances for installed packages.
42
30
  self.package_configs = {}
43
31
 
44
32
  # Whether the registry is populated.
45
- self.packages_ready = self.models_ready = self.ready = False
33
+ self.packages_ready = self.ready = False
46
34
 
47
35
  # Lock for thread-safe population.
48
36
  self._lock = threading.RLock()
49
37
  self.loading = False
50
38
 
51
- # Maps ("package_label", "modelname") tuples to lists of functions to be
52
- # called when the corresponding model is ready. Used by this class's
53
- # `lazy_model_operation()` and `do_pending_operations()` methods.
54
- self._pending_operations = defaultdict(list)
55
-
56
39
  # Populate packages and models, unless it's the main registry.
57
40
  if installed_packages is not None:
58
41
  self.populate(installed_packages)
@@ -87,7 +70,7 @@ class PackagesRegistry:
87
70
  if isinstance(entry, PackageConfig):
88
71
  # Some instances of the registry pass in the
89
72
  # PackageConfig directly...
90
- self.register_config(entry)
73
+ self.register_config(package_config=entry)
91
74
  else:
92
75
  try:
93
76
  import_module(f"{entry}.{CONFIG_MODULE_NAME}")
@@ -104,9 +87,8 @@ class PackagesRegistry:
104
87
 
105
88
  if not entry_config:
106
89
  # Use PackageConfig class as-is, without any customization.
107
- entry_config = self.register_config(
108
- PackageConfig, module_name=entry
109
- )
90
+ auto_package_config = PackageConfig(entry)
91
+ entry_config = self.register_config(auto_package_config)
110
92
 
111
93
  # Make sure we have the same number of configs as we have installed packages
112
94
  if len(self.package_configs) != len(installed_packages):
@@ -133,10 +115,6 @@ class PackagesRegistry:
133
115
  for package_config in self.get_package_configs():
134
116
  package_config.ready()
135
117
 
136
- self.clear_cache()
137
-
138
- self.models_ready = True
139
-
140
118
  self.ready = True
141
119
 
142
120
  def check_packages_ready(self):
@@ -150,11 +128,6 @@ class PackagesRegistry:
150
128
  settings.INSTALLED_PACKAGES
151
129
  raise PackageRegistryNotReady("Packages aren't loaded yet.")
152
130
 
153
- def check_models_ready(self):
154
- """Raise an exception if all models haven't been imported yet."""
155
- if not self.models_ready:
156
- raise PackageRegistryNotReady("Models aren't loaded yet.")
157
-
158
131
  def get_package_configs(self):
159
132
  """Import applications and return an iterable of app configs."""
160
133
  self.check_packages_ready()
@@ -177,102 +150,6 @@ class PackagesRegistry:
177
150
  break
178
151
  raise LookupError(message)
179
152
 
180
- # This method is performance-critical at least for Plain's test suite.
181
- @functools.cache
182
- def get_models(
183
- self, *, package_label="", include_auto_created=False, include_swapped=False
184
- ):
185
- """
186
- Return a list of all installed models.
187
-
188
- By default, the following models aren't included:
189
-
190
- - auto-created models for many-to-many relations without
191
- an explicit intermediate table,
192
- - models that have been swapped out.
193
-
194
- Set the corresponding keyword argument to True to include such models.
195
- """
196
- self.check_models_ready()
197
-
198
- result = []
199
-
200
- # Get models for a single package
201
- if package_label:
202
- package_models = self.all_models[package_label]
203
- for model in package_models.values():
204
- if model._meta.auto_created and not include_auto_created:
205
- continue
206
- if model._meta.swapped and not include_swapped:
207
- continue
208
- result.append(model)
209
- return result
210
-
211
- # Get models for all packages
212
- for package_models in self.all_models.values():
213
- for model in package_models.values():
214
- if model._meta.auto_created and not include_auto_created:
215
- continue
216
- if model._meta.swapped and not include_swapped:
217
- continue
218
- result.append(model)
219
-
220
- return result
221
-
222
- def get_model(self, package_label, model_name=None, require_ready=True):
223
- """
224
- Return the model matching the given package_label and model_name.
225
-
226
- As a shortcut, package_label may be in the form <package_label>.<model_name>.
227
-
228
- model_name is case-insensitive.
229
-
230
- Raise LookupError if no application exists with this label, or no
231
- model exists with this name in the application. Raise ValueError if
232
- called with a single argument that doesn't contain exactly one dot.
233
- """
234
- if require_ready:
235
- self.check_models_ready()
236
- else:
237
- self.check_packages_ready()
238
-
239
- if model_name is None:
240
- package_label, model_name = package_label.split(".")
241
-
242
- # package_config = self.get_package_config(package_label)
243
-
244
- # if not require_ready and package_config.models is None:
245
- # package_config.import_models()
246
-
247
- package_models = self.all_models[package_label]
248
- return package_models[model_name.lower()]
249
-
250
- def register_model(self, package_label, model):
251
- # Since this method is called when models are imported, it cannot
252
- # perform imports because of the risk of import loops. It mustn't
253
- # call get_package_config().
254
- model_name = model._meta.model_name
255
- app_models = self.all_models[package_label]
256
- if model_name in app_models:
257
- if (
258
- model.__name__ == app_models[model_name].__name__
259
- and model.__module__ == app_models[model_name].__module__
260
- ):
261
- warnings.warn(
262
- f"Model '{package_label}.{model_name}' was already registered. Reloading models is not "
263
- "advised as it can lead to inconsistencies, most notably with "
264
- "related models.",
265
- RuntimeWarning,
266
- stacklevel=2,
267
- )
268
- else:
269
- raise RuntimeError(
270
- f"Conflicting '{model_name}' models in application '{package_label}': {app_models[model_name]} and {model}."
271
- )
272
- app_models[model_name] = model
273
- self.do_pending_operations(model)
274
- self.clear_cache()
275
-
276
153
  def get_containing_package_config(self, object_name):
277
154
  """
278
155
  Look for an app config containing a given object.
@@ -292,108 +169,7 @@ class PackagesRegistry:
292
169
  if candidates:
293
170
  return sorted(candidates, key=lambda ac: -len(ac.name))[0]
294
171
 
295
- def get_registered_model(self, package_label, model_name):
296
- """
297
- Similar to get_model(), but doesn't require that an app exists with
298
- the given package_label.
299
-
300
- It's safe to call this method at import time, even while the registry
301
- is being populated.
302
- """
303
- model = self.all_models[package_label].get(model_name.lower())
304
- if model is None:
305
- raise LookupError(f"Model '{package_label}.{model_name}' not registered.")
306
- return model
307
-
308
- @functools.cache
309
- def get_swappable_settings_name(self, to_string):
310
- """
311
- For a given model string (e.g. "auth.User"), return the name of the
312
- corresponding settings name if it refers to a swappable model. If the
313
- referred model is not swappable, return None.
314
-
315
- This method is decorated with @functools.cache because it's performance
316
- critical when it comes to migrations. Since the swappable settings don't
317
- change after Plain has loaded the settings, there is no reason to get
318
- the respective settings attribute over and over again.
319
- """
320
- to_string = to_string.lower()
321
- for model in self.get_models(include_swapped=True):
322
- swapped = model._meta.swapped
323
- # Is this model swapped out for the model given by to_string?
324
- if swapped and swapped.lower() == to_string:
325
- return model._meta.swappable
326
- # Is this model swappable and the one given by to_string?
327
- if model._meta.swappable and model._meta.label_lower == to_string:
328
- return model._meta.swappable
329
- return None
330
-
331
- def clear_cache(self):
332
- """
333
- Clear all internal caches, for methods that alter the app registry.
334
-
335
- This is mostly used in tests.
336
- """
337
- # Call expire cache on each model. This will purge
338
- # the relation tree and the fields cache.
339
- self.get_models.cache_clear()
340
- if self.ready:
341
- # Circumvent self.get_models() to prevent that the cache is refilled.
342
- # This particularly prevents that an empty value is cached while cloning.
343
- for package_models in self.all_models.values():
344
- for model in package_models.values():
345
- model._meta._expire_cache()
346
-
347
- def lazy_model_operation(self, function, *model_keys):
348
- """
349
- Take a function and a number of ("package_label", "modelname") tuples, and
350
- when all the corresponding models have been imported and registered,
351
- call the function with the model classes as its arguments.
352
-
353
- The function passed to this method must accept exactly n models as
354
- arguments, where n=len(model_keys).
355
- """
356
- # Base case: no arguments, just execute the function.
357
- if not model_keys:
358
- function()
359
- # Recursive case: take the head of model_keys, wait for the
360
- # corresponding model class to be imported and registered, then apply
361
- # that argument to the supplied function. Pass the resulting partial
362
- # to lazy_model_operation() along with the remaining model args and
363
- # repeat until all models are loaded and all arguments are applied.
364
- else:
365
- next_model, *more_models = model_keys
366
-
367
- # This will be executed after the class corresponding to next_model
368
- # has been imported and registered. The `func` attribute provides
369
- # duck-type compatibility with partials.
370
- def apply_next_model(model):
371
- next_function = partial(apply_next_model.func, model)
372
- self.lazy_model_operation(next_function, *more_models)
373
-
374
- apply_next_model.func = function
375
-
376
- # If the model has already been imported and registered, partially
377
- # apply it to the function now. If not, add it to the list of
378
- # pending operations for the model, where it will be executed with
379
- # the model class as its sole argument once the model is ready.
380
- try:
381
- model_class = self.get_registered_model(*next_model)
382
- except LookupError:
383
- self._pending_operations[next_model].append(apply_next_model)
384
- else:
385
- apply_next_model(model_class)
386
-
387
- def do_pending_operations(self, model):
388
- """
389
- Take a newly-prepared model and pass it to each function waiting for
390
- it. This is called at the very end of Packages.register_model().
391
- """
392
- key = model._meta.package_label, model._meta.model_name
393
- for function in self._pending_operations.pop(key, []):
394
- function(model)
395
-
396
- def register_config(self, package_config, module_name=""):
172
+ def register_config(self, package_config):
397
173
  """
398
174
  Add a config to the registry.
399
175
 
@@ -403,19 +179,6 @@ class PackagesRegistry:
403
179
  class Config(PackageConfig):
404
180
  pass
405
181
  """
406
- if not module_name:
407
- module_name = package_config.__module__
408
-
409
- # If it is in .config like expected, return the parent module name
410
- if module_name.endswith(f".{CONFIG_MODULE_NAME}"):
411
- module_name = module_name[: -len(CONFIG_MODULE_NAME) - 1]
412
-
413
- if isinstance(package_config, type) and issubclass(
414
- package_config, PackageConfig
415
- ):
416
- # A class was passed, so init it
417
- package_config = package_config(module_name)
418
-
419
182
  if package_config.label in self.package_configs:
420
183
  raise ImproperlyConfigured(
421
184
  f"Package labels aren't unique, duplicates: {package_config.label}"
@@ -427,4 +190,18 @@ class PackagesRegistry:
427
190
 
428
191
 
429
192
  packages_registry = PackagesRegistry(installed_packages=None)
430
- register_config = packages_registry.register_config
193
+
194
+
195
+ def register_config(package_config_class):
196
+ """A decorator to register a PackageConfig subclass."""
197
+ module_name = package_config_class.__module__
198
+
199
+ # If it is in .config like expected, return the parent module name
200
+ if module_name.endswith(f".{CONFIG_MODULE_NAME}"):
201
+ module_name = module_name[: -len(CONFIG_MODULE_NAME) - 1]
202
+
203
+ package_config = package_config_class(module_name)
204
+
205
+ packages_registry.register_config(package_config)
206
+
207
+ return package_config_class
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plain
3
- Version: 0.26.0
3
+ Version: 0.27.0
4
4
  Summary: A web framework for building products with Python.
5
5
  Author-email: Dave Gaeddert <dave.gaeddert@dropseed.dev>
6
6
  License-File: LICENSE
@@ -62,7 +62,7 @@ plain/logs/utils.py,sha256=9UzdCCQXJinGDs71Ngw297mlWkhgZStSd67ya4NOW98,1257
62
62
  plain/packages/README.md,sha256=Vq1Nw3mmEmZ2IriQavuVi4BjcQC2nb8k7YIbnm8QjIg,799
63
63
  plain/packages/__init__.py,sha256=OpQny0xLplPdPpozVUUkrW2gB-IIYyDT1b4zMzOcCC4,160
64
64
  plain/packages/config.py,sha256=Gmu7QW4Z3Cx9_d7N2D5o7t292t7vAOE8aL-3yO7sGqc,3327
65
- plain/packages/registry.py,sha256=UEagFzHXCSuGeMlz2E1JLj0fgigOR89i5yVZe8Pq9Ds,17589
65
+ plain/packages/registry.py,sha256=Aklno7y7UrBZlidtUR_YO3B5xqF46UbUtalReNcYHm8,7937
66
66
  plain/preflight/README.md,sha256=-PKVd0RBMh4ROiMkegPS2PgvT1Kq9qqN1KfNkmUSdFc,177
67
67
  plain/preflight/__init__.py,sha256=H-TNRvaddPtOGmv4RXoc1fxDV1AOb7_K3u7ECF8mV58,607
68
68
  plain/preflight/files.py,sha256=wbHCNgps7o1c1zQNBd8FDCaVaqX90UwuvLgEQ_DbUpY,510
@@ -134,8 +134,8 @@ plain/views/forms.py,sha256=RhlaUcZCkeqokY_fvv-NOS-kgZAG4XhDLOPbf9K_Zlc,2691
134
134
  plain/views/objects.py,sha256=g5Lzno0Zsv0K449UpcCtxwCoO7WMRAWqKlxxV2V0_qg,8263
135
135
  plain/views/redirect.py,sha256=9zHZgKvtSkdrMX9KmsRM8hJTPmBktxhc4d8OitbuniI,1724
136
136
  plain/views/templates.py,sha256=cBkFNCSXgVi8cMqQbhsqJ4M_rIQYVl8cUvq9qu4YIes,1951
137
- plain-0.26.0.dist-info/METADATA,sha256=ubQaY6xdMzXNiRH6AvYXOWNyOdmthru0UB3-AKlPnxU,319
138
- plain-0.26.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
139
- plain-0.26.0.dist-info/entry_points.txt,sha256=DHHprvufgd7xypiBiqMANYRnpJ9xPPYhYbnPGwOkWqE,40
140
- plain-0.26.0.dist-info/licenses/LICENSE,sha256=m0D5O7QoH9l5Vz_rrX_9r-C8d9UNr_ciK6Qwac7o6yo,3175
141
- plain-0.26.0.dist-info/RECORD,,
137
+ plain-0.27.0.dist-info/METADATA,sha256=5bkOqMEQNCnkyEx011gMDQNmLjzncCOXJ2zPGti0HHo,319
138
+ plain-0.27.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
139
+ plain-0.27.0.dist-info/entry_points.txt,sha256=DHHprvufgd7xypiBiqMANYRnpJ9xPPYhYbnPGwOkWqE,40
140
+ plain-0.27.0.dist-info/licenses/LICENSE,sha256=m0D5O7QoH9l5Vz_rrX_9r-C8d9UNr_ciK6Qwac7o6yo,3175
141
+ plain-0.27.0.dist-info/RECORD,,
File without changes