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.

resource.py 2.5KB

1 year ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. class Model:
  2. """
  3. A base class for representing a single object on the server.
  4. """
  5. id_attribute = 'Id'
  6. def __init__(self, attrs=None, client=None, collection=None):
  7. #: A client pointing at the server that this object is on.
  8. self.client = client
  9. #: The collection that this model is part of.
  10. self.collection = collection
  11. #: The raw representation of this object from the API
  12. self.attrs = attrs
  13. if self.attrs is None:
  14. self.attrs = {}
  15. def __repr__(self):
  16. return f"<{self.__class__.__name__}: {self.short_id}>"
  17. def __eq__(self, other):
  18. return isinstance(other, self.__class__) and self.id == other.id
  19. def __hash__(self):
  20. return hash(f"{self.__class__.__name__}:{self.id}")
  21. @property
  22. def id(self):
  23. """
  24. The ID of the object.
  25. """
  26. return self.attrs.get(self.id_attribute)
  27. @property
  28. def short_id(self):
  29. """
  30. The ID of the object, truncated to 12 characters.
  31. """
  32. return self.id[:12]
  33. def reload(self):
  34. """
  35. Load this object from the server again and update ``attrs`` with the
  36. new data.
  37. """
  38. new_model = self.collection.get(self.id)
  39. self.attrs = new_model.attrs
  40. class Collection:
  41. """
  42. A base class for representing all objects of a particular type on the
  43. server.
  44. """
  45. #: The type of object this collection represents, set by subclasses
  46. model = None
  47. def __init__(self, client=None):
  48. #: The client pointing at the server that this collection of objects
  49. #: is on.
  50. self.client = client
  51. def __call__(self, *args, **kwargs):
  52. raise TypeError(
  53. "'{}' object is not callable. You might be trying to use the old "
  54. "(pre-2.0) API - use docker.APIClient if so."
  55. .format(self.__class__.__name__))
  56. def list(self):
  57. raise NotImplementedError
  58. def get(self, key):
  59. raise NotImplementedError
  60. def create(self, attrs=None):
  61. raise NotImplementedError
  62. def prepare_model(self, attrs):
  63. """
  64. Create a model from a set of attributes.
  65. """
  66. if isinstance(attrs, Model):
  67. attrs.client = self.client
  68. attrs.collection = self
  69. return attrs
  70. elif isinstance(attrs, dict):
  71. return self.model(attrs=attrs, client=self.client, collection=self)
  72. else:
  73. raise Exception("Can't create %s from %s" %
  74. (self.model.__name__, attrs))