Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.py 1.6KB

1 year ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import functools
  2. from collections import namedtuple
  3. def make_model_tuple(model):
  4. """
  5. Take a model or a string of the form "app_label.ModelName" and return a
  6. corresponding ("app_label", "modelname") tuple. If a tuple is passed in,
  7. assume it's a valid model tuple already and return it unchanged.
  8. """
  9. try:
  10. if isinstance(model, tuple):
  11. model_tuple = model
  12. elif isinstance(model, str):
  13. app_label, model_name = model.split(".")
  14. model_tuple = app_label, model_name.lower()
  15. else:
  16. model_tuple = model._meta.app_label, model._meta.model_name
  17. assert len(model_tuple) == 2
  18. return model_tuple
  19. except (ValueError, AssertionError):
  20. raise ValueError(
  21. "Invalid model reference '%s'. String model references "
  22. "must be of the form 'app_label.ModelName'." % model
  23. )
  24. def resolve_callables(mapping):
  25. """
  26. Generate key/value pairs for the given mapping where the values are
  27. evaluated if they're callable.
  28. """
  29. for k, v in mapping.items():
  30. yield k, v() if callable(v) else v
  31. def unpickle_named_row(names, values):
  32. return create_namedtuple_class(*names)(*values)
  33. @functools.lru_cache
  34. def create_namedtuple_class(*names):
  35. # Cache type() with @lru_cache since it's too slow to be called for every
  36. # QuerySet evaluation.
  37. def __reduce__(self):
  38. return unpickle_named_row, (names, tuple(self))
  39. return type(
  40. "Row",
  41. (namedtuple("Row", names),),
  42. {"__reduce__": __reduce__, "__slots__": ()},
  43. )