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