def update_model(cls, model: ModelBO, force_insert=False): """Update a model to ModelDB and GridFS. The function will check the existence of the provided model. It will invoke the update. Note that this function will have not effect for static profiling result and dynamic profiling result. Please see `register_static_profiling_result` and ` Args: model (ModelBO): model business object to be updated. The model must exist in the ModelDB based on its `id`. Otherwise, you should set `force_insert` to be `True`. force_insert (bool: `True`, optional): Force insert flag for ModelDB. The model will force to insert regardless its existence. Return: True for successfully update, False otherwise. Raises: ValueError: If `model.id` does not exist in ModelDB, and `force_insert` is not set. """ # check for the existence of Model if cls.__model_DAO.exists_by_id(model.id): model_po_new = model.to_model_do() model_po = cls.__model_DAO.get_model_by_id(model.id) # if weight changes, save all without patch if model_po_new.weight is not None and model_po_new.weight != model_po.weight: return bool(cls.__model_DAO.save_model(model_po_new)) # build arguments valid_keys = [ 'name', 'framework', 'engine', 'version', 'dataset', 'accuracy', 'weight', 'task', 'inputs', 'outputs', 'status' ] kwargs = dict() for valid_key in valid_keys: new_value = getattr(model_po_new, valid_key) if new_value is not None and new_value != getattr( model_po, valid_key): kwargs[valid_key] = new_value # if kwargs is empty, not update if len(kwargs) == 0: return False return bool(cls.__model_DAO.update_model(model.id, **kwargs)) # return bool(cls.__model_DAO.update_model(model_po_new)) else: # if `force_insert` is set if force_insert: model_po = model.to_model_do() return bool(cls.__model_DAO.save_model(model_po)) else: raise ValueError( 'Model ID {} does not exist. You may change the ID or set `force_insert=True` ' 'when call.'.format(model.id))
def post_model(cls, model: ModelBO): """Register a model into ModelDB and GridFS. `model.id` should be set as `None`, otherwise, the function will raise a `ValueError`. Args: model (ModelBO): model business object to be registered Return: bool: True if successful, False otherwise Raises: BadRequestValueException: If `model.id` is not None. ServiceException: If model has exists with the same primary keys (name, framework, engine and version). """ # check model id if model.id is not None: raise BadRequestValueException( 'field `id` is expected `None`, but got {}. You should use `update_model` for a existing ' 'model BO'.format(model.id)) model_po = model.to_model_do() if cls.__model_DAO.exists_by_primary_keys(name=model_po.name, framework=model_po.framework, engine=model_po.engine, version=model_po.version): raise ServiceException( f'Model business object with primary keys name={model_po.name}, framework={model_po.framework}, ' f'engine={model_po.engine}, version={model_po.version} has exists.' ) return bool(cls.__model_DAO.save_model(model_po))