def set_property(self, name, value, update_session=True): """Create or set the value of a property. Returns `True` if the property was created or updated, or `False` if there were no changes to the value of the property. Args: name (str): Name of the property to create or update value (any): Value of the property. This can be any type of JSON serializable data update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns: `bool` """ if type(value) == datetime: value = value.isoformat() else: value = value try: prop = self.get_property(name) if prop.value == value: return False prop.value = value except AttributeError: prop = ResourceProperty() prop.resource_id = self.id prop.name = name prop.value = value if update_session: db.session.add(prop) return True
def create(cls, resource_id, *, account_id, properties=None, tags=None, location=None, auto_add=True, auto_commit=False): """Creates a new Resource object with the properties and tags provided Args: resource_id (str): Unique identifier for the resource object account_id (int): Account ID which owns the resource properties (dict): Dictionary of properties for the resource object. tags (dict): Key / value dictionary of tags. Values must be `str` types location (str): Location of the resource, if applicable auto_add (bool): Automatically add the new resource to the DB session. Default: True auto_commit (bool): Automatically commit the change to the database. Default: False """ if cls.get(resource_id): raise ResourceException('Resource {} already exists'.format(resource_id)) res = Resource() res.resource_id = resource_id res.account_id = account_id res.location = location res.resource_type_id = ResourceType.get(cls.resource_type).resource_type_id if properties: for name, value in properties.items(): prop = ResourceProperty() prop.resource_id = res.resource_id prop.name = name prop.value = value.isoformat() if type(value) == datetime else value res.properties.append(prop) db.session.add(prop) if tags: for key, value in tags.items(): if type(value) != str: raise ValueError('Invalid object type for tag value: {}'.format(key)) tag = Tag() tag.resource_id = resource_id tag.key = key tag.value = value res.tags.append(tag) db.session.add(tag) if auto_add: db.session.add(res) if auto_commit: db.session.commit() return cls.get(res.resource_id) else: return cls(res)