def common_create(appname, modelname, temp_dict): Model_Name = classing_model(modelname) try: temp_dict = CommonBase.clean_data(modelname, temp_dict) except ParamError as e: return json_response_error(PARAM_ERROR, msg=e.msg) # when save data, filter some useless data pop_list = [ 'id', 'last_release_ec2', 'last_release_local', 'release', 'is_upload_local', 'is_upload_ec2'] for key in pop_list: temp_dict.pop(key, None) if hasattr(Model_Name, "fields_check"): try: temp_dict = get_valid_params(temp_dict, Model_Name.fields_check) except ParamError as e: return json_response_error(PARAM_ERROR, msg=e.msg) temp_dict['first_created'] = temp_dict['last_modified'] = now_timestamp() #this is a factory function, to check some save data before insert if need (check_success, msg) = check_save_dict(appname, modelname, temp_dict) if not check_success: return json_response_error(PARAM_ERROR, msg=msg) insert_id = Model_Name.insert(appname, temp_dict) temp_dict['id'] = insert_id # if the model has ref icon and rule, increase the reference inc_icon(appname, modelname, temp_dict) inc_rule(appname, modelname, temp_dict) return json_response_ok(temp_dict)
def common_check_unique(appname, modelname, temp_dict): Model_Name = classing_model(modelname) method = temp_dict.pop('method', None) temp_dict.pop('original_value', None) item_id = temp_dict.pop('id', 0) # when pop method and id, only "unique_key": "value" left name = temp_dict.keys()[0] value = temp_dict.get(name) unique_pass = False if hasattr(Model_Name, "unique"): unique_list = Model_Name.unique if name not in unique_list: return json_response_error(PARAM_ERROR, msg="%s not exist" % name) if method == 'add': if not Model_Name.find_one(appname, temp_dict): unique_pass = True elif method == 'update': old_item = Model_Name.find_one(appname, {'id': int(item_id)}) if not Model_Name.find_one(appname, temp_dict): unique_pass = True else: old_val = old_item.get(name) # when update if old title not change unique_pass = True if old_val == value else False else: return json_response_error(PARAM_ERROR, msg="method is not apply") else: unique_pass = True return json_response_ok({"unique": unique_pass})
def clean_data(cls, modelname, req_dict): ''' notice:the temp_dict pass in, check order field and id field and put it into a new children_list; now the list req only {'id': 1, 'order':2} for default ''' Model_Class = classing_model(modelname) if hasattr(Model_Class, "one2one"): one_refs = Model_Class.one2one for key in one_refs: ori_ref = req_dict.get(key) if ori_ref: req_dict[key] = {'id': ori_ref.get('id')} children = Model_Class.relation.get("children") if not children: return req_dict for child in children: reqlist = req_dict.get(child) if reqlist: saved_list = [] for child_info in reqlist: child_dict = {} child_dict['id'] = child_info.get('id') try: child_dict['order'] = int(child_info.get('order', 0)) except: raise ParamError('order format error') saved_list.append(child_dict) req_dict[child] = saved_list return req_dict
def offline(appname, modelname, item_ids, server): Model_Class = classing_model(modelname) items = Model_Class.find( appname, {'id': {'$in': item_ids}}, fields={'_id': 0}, toarray=True) if not items: return json_response_error(PARAM_ERROR, msg="no item find") results = offline_data(appname, modelname, server, items) status = results[0] data = {} data["success"] = results[1] data["failed"] = results[2] data['userlog'] = [common_filter(i) for i in data.get('success')] data['memo'] = 'offline from %s' % server if status == -1: return json_response_error(PARAM_ERROR, msg="UNKNOWN UPLOAD SERVER") elif status == 0: if server == _ADMIN: data['success_list'] = data.get('success') data['failed_list'] = data.get('failed') suc_ids = fail_ids = [] if data["failed"]: fail_ids = [i.get('id') for i in data.get('failed')] if data["success"]: suc_ids = [i.get('id') for i in data.get('success')] data["success"] = suc_ids data["failed"] = fail_ids data['memo'] = 'delete it from admin' return json_response_ok(data, msg="delete successfully") else: return json_response_error(status, data, msg="del error")
def get_theme( self, theme_ids, server=_LOCAL, isfree=True, size=Image.Iph4_5s): ''' get theme by theme ids and paid ''' theme_list = [] Theme = classing_model('theme') theme_infos = Theme.find( self.appname, cond={'id': {'$in': theme_ids}, 'isfree': isfree, 'size': size}, fields={'_id': 0}, toarray=True) if not theme_infos: return theme_list for theme_id in theme_ids: for theme_info in theme_infos: if theme_id == theme_info.get('id'): icon_url = fetch_icon_url( self.appname, theme_info.get('icon'), server) banner_url = fetch_icon_url( self.appname, theme_info.get('logo'), server) locale_titles = theme_info.get('themelocale') theme_dict = { 'type': 'theme', 'themeId': theme_id, 'name': theme_info.get('name'), 'titles': self.localize_titles(locale_titles), 'downloadUrl': banner_url, 'thumbnailUrl': icon_url, 'price': theme_info.get('prize', ''), 'productId': theme_info.get('paidID', '')} theme_list.append(theme_dict) return theme_list
def ref_topmodel(appname, model_id, model_name, object_link=[]): ''' notice: pass in object links, give back the preset ids if len(object) is 1, get it easy patch: in push admin, some model has modify pattern, such as push speeddial, speeddial_modify ''' topmodel = object_link[-1] TopModel = classing_model(topmodel) topmodel_list = [] length = len(object_link) cond = {} topmodel_ids = [] if length == 1: cond = NameFactory.combine_cond(model_name, model_id) topmodel_list = TopModel.find( appname, cond, fields={'_id': 0}, toarray=True) if topmodel_list: topmodel_ids = [t.get('id') for t in topmodel_list] else: index = 0 start_model = model_name next_ids = [] next_ids.append(model_id) while index < length: next_ids = _get_ids( appname, next_ids, start_model, object_link[index]) start_model = object_link[index] index = index + 1 topmodel_ids = next_ids return topmodel_ids
def get_themefolder(self, folder_ids, server, isfree, size=Image.Iph4_5s): folder_list = [] if not folder_ids: return folder_list ThemeFolder = classing_model('themefolder') folders = ThemeFolder.find( self.appname, cond={'id': {'$in': folder_ids}, 'isfree': isfree, 'size': size}, fields={'_id': 0}, toarray=True) if not folders: return folder_list for folder_id in folder_ids: for folder in folders: if folder_id == folder.get('id'): themes = sorted( folder.get('theme'), key=lambda x: x['order']) theme_ids = [t.get('id') for t in themes] theme_infos = self.get_theme( theme_ids, server=server, isfree=isfree, size=size) icon_url = fetch_icon_url( self.appname, folder.get('icon'), server) locale_titles = folder.get('themelocale') folder_dict = { 'type': 'folder', 'folderId': folder.get('id'), 'name': folder.get('name'), 'titles': self.localize_titles(locale_titles), 'thumbnailUrl': icon_url, 'themes': theme_infos} folder_list.append(folder_dict) return folder_list
def list_base(cls, appname, model_name, query_dict): ''' notice: get the list data of one model ''' return_data = {} Model_Name = classing_model(model_name) cond = {} list_api = Model_Name.list_api if list_api.get("search_fields"): search_fields = list_api["search_fields"] cond = _search_cond(appname, query_dict, search_fields) fields = list_api["fields"] fields["_id"] = 0 sort_field = query_dict['sort_field'] sort_way = query_dict['sort_way'] pageindex = query_dict['pageindex'] pagesize = query_dict['pagesize'] results = Model_Name.find( appname, cond, fields=fields).sort( sort_field, sort_way).skip( pageindex * pagesize).limit(pagesize) total = Model_Name.find(appname, cond).count() return_data["results"] = results return_data["total"] = total return return_data
def _unrefered_parents(appname, parent_model, child_model, model_id, confirm): return_data = {} Parent_Model = classing_model(parent_model) pattern = child_model + ".id" # id field in parent model parent_items = Parent_Model.find( appname, {pattern: model_id}, fields={"_id": 0}, toarray=True) if parent_items: for pitem in parent_items: upt_val = None # 父model存在多个子model引用:[{"id":1},{"id":2}] child_info = pitem.get(child_model) if isinstance(child_info, types.ListType): for id_dict in child_info: if id_dict.get("id") == model_id: if confirm: child_info.remove(id_dict) upt_val = child_info else: return_data.update({'status': DATA_DELETE_COMFIRM}) return return_data if isinstance(child_info, types.DictType) and child_info: # 父model对只引用单条model:{"id":1} return_data.update({'status': DATA_RELETED_BY_OTHER}) return return_data Parent_Model.update( appname, {"id": pitem["id"]}, {child_model: upt_val}) else: _LOGGER.info("parent %s has no %s id", parent_model, child_model)
def _del_data_ec2(appname, modelname, items): status = 0 delete_success = [] delete_failed = [] Model_Class = classing_model(modelname) up_table = get_upload_table(modelname) Ec2_db = ArmoryMongo[_EC2] for item in items: rawid = item.get('id') if Ec2_db[up_table].find_one({"id": rawid}): upt_status = { 'is_upload_ec2': False, 'last_release_ec2': 0, 'release': UploadStatus.UNUPLOAD_EC2} Model_Class.update( appname, {"id": rawid}, upt_status) item_suc = refresh_status(appname, modelname, rawid) delete_success.append(item_suc) Ec2_db[up_table].remove({"id": rawid}) _LOGGER.info("id:%d delete from ec2 success", rawid) else: status = DUPLICATE_DELETE item_fail = refresh_status(appname, modelname, rawid) delete_failed.append(item_fail) return status, delete_success, delete_failed
def _del_data_admin(appname, modelname, items): status = 0 delete_success = [] delete_failed = [] Model_Class = classing_model(modelname) upload_table = get_upload_table(modelname) Local_db = ArmoryMongo[_LOCAL] for item in items: rawid = item.get('id') item_local = Local_db[upload_table].find_one( {"id": rawid}, fields={"_id": 0}) if item_local: status = ONLINE_DATA_UNDELETE delete_failed.append(item) _LOGGER.error("id:%d should delete from local first" % rawid) else: release_rule(appname, modelname, rawid) model_dict = Model_Class.find_one(appname, {'id': rawid}) _LOGGER.info(model_dict) CommonBase.dec_icon(appname, modelname, model_dict, rawid) # de referenced icon and rule delete_success.append(model_dict) Model_Class.remove(appname, {"id": rawid}) _LOGGER.info("id:%d delete from admin success", rawid) return status, delete_success, delete_failed
def build_unqiue_cond(modelname, save_dict): ModelClass = classing_model(modelname) cond = {} unique = ModelClass.unique if len(unique) > 1: # unique should be list type # like ['a', ('b','c')] ----> # {"$or": [{"a":"xx"}, "$and":[{"b":"yy"}, {"c": "zz"}]]} or_cond = [] for u in unique: if not isinstance(u, str) and not isinstance(u, unicode): and_cond = [] for ui in u: if save_dict.get(ui): and_cond.append({ui: save_dict[ui]}) or_cond.append(and_cond) else: if save_dict.get(u): or_cond.append({u: save_dict[u]}) cond['$or'] = or_cond else: one = unique[0] if not isinstance(one, str) and not isinstance(one, unicode): and_cond = [] for ui in one: if save_dict.get(ui): and_cond.append({ui: save_dict[ui]}) cond['$and'] = and_cond else: cond[one] = save_dict[one] return cond
def _del_data_local(appname, modelname, items): status = 0 delete_success = [] delete_failed = [] Model_Class = classing_model(modelname) up_table = get_upload_table(modelname) Local_db = ArmoryMongo[_LOCAL] Ec2_db = ArmoryMongo[_EC2] for item in items: rawid = item.get('id') if not Ec2_db[up_table].find_one({"id": rawid}): if Local_db[up_table].find_one({"id": rawid}, fields={"_id": 0}): upt_status = {} upt_status = { 'is_upload_local': False, 'release': UploadStatus.UNUPLOAD_LOCAL, 'last_release_local': 0} Model_Class.update(appname, {"id": rawid}, upt_status) Local_db[up_table].remove({"id": rawid}) item_suc = refresh_status(appname, modelname, rawid) delete_success.append(item_suc) _LOGGER.info("id:%d delete from local success", rawid) else: status = DUPLICATE_DELETE delete_failed.append(item) else: status = ONLINE_DATA_UNDELETE, item_fail = refresh_status(appname, modelname, rawid) delete_failed.append(item_fail) _LOGGER.error("id:%d should delete from ec2 first" % rawid) return status, delete_success, delete_failed
def common_update(appname, modelname, temp_dict, item_id): Model_Name = classing_model(modelname) temp_dict.pop("id", 0) try: temp_dict = CommonBase.clean_data(modelname, temp_dict) except ParamError as e: return json_response_error(PARAM_ERROR, msg=e.msg) if hasattr(Model_Name, "fields_check"): try: temp_dict = get_valid_params(temp_dict, Model_Name.fields_check) except ParamError as e: return json_response_error(PARAM_ERROR, msg=e.msg) cond = {"id": int(item_id)} temp_dict['last_modified'] = now_timestamp() # if the model has release field if check_release(modelname): temp_dict['release'] = UploadStatus.UNUPLOAD_LOCAL # find the old item before update, aim to track icon and rule old_item = Model_Name.find_one(appname, {'id': item_id}, {'_id': 0}) #this is a factory function, to check some save data before save if need (check_success, msg) = check_save_dict( appname, modelname, temp_dict, item_id) if not check_success: return json_response_error(PARAM_ERROR, msg=msg) Model_Name.update(appname, cond, temp_dict) temp_dict['id'] = item_id # if model has refered icon and rule mod_icon(appname, modelname, temp_dict, old_item) mod_rule(appname, modelname, temp_dict, old_item) return json_response_ok(temp_dict)
def upload2server(appname, modelname, item, server): Model_Class = classing_model(modelname) upload_table = get_upload_table(modelname) Remote_db = ArmoryMongo[server] # update status upload to local results = package_data(appname, modelname, item, server) # param1: success/failed true/false param2:msg param3:return dict if not results[0]: return False, results[1] else: item_id = item.get('id') cond = {"id": item_id} res_dict = results[2] is_upload_server = "is_upload_%s" % server last_release_server = "last_release_%s" % server upt_status = {} upt_status[is_upload_server] = True upt_status[last_release_server] = now_timestamp() if server == _LOCAL: upt_status['release'] = UploadStatus.UNUPLOAD_EC2 if server == _EC2: upt_status['release'] = UploadStatus.NOMORAL Model_Class.update(appname, cond, upt_status) save_data = pack_save_data(res_dict) Remote_db[upload_table].update(cond, save_data, True) return True, results[1]
def release_rule(appname, modelname, rawid): Model_Class = classing_model(modelname) item = Model_Class.find_one(appname, {'id': rawid}) rule_dict = item.get('aosruledata') rule_id = rule_dict.get('id') unrefered_data = { 'modelName': modelname, 'id': rawid, 'modelField': 'aosruledata'} unrefered_rule(appname, rule_id, 'rule', unrefered_data)
def viewdetail(cls, appname, model_name, model_dict): ''' 输入model name,如果该model包含子model,将按照order字段 将子model排序 ''' children = {} Model_Class = classing_model(str(model_name)) if Model_Class.relation: children = Model_Class.relation.get("children") # if model has several children, eg: predata has searcherfolder, # bookmark bookmarkfolder if children: for key in children: Child_Model = classing_model(str(key)) shortinfo_list = model_dict.get(key) if not shortinfo_list: continue new_children_list = [] for shortinfo in shortinfo_list: child_id = shortinfo["id"] child_detail = Child_Model.find_one( appname, {"id": child_id}, fields={"_id": 0}) if child_detail: for short in shortinfo: child_detail[short] = shortinfo[short] new_children_list.append(child_detail) new_children_list = sorted( new_children_list, key=itemgetter("order")) model_dict[key] = new_children_list if hasattr(Model_Class, "one2one"): # if model refere to other model,eg:speeddial with icon single_refs = Model_Class.one2one for single in single_refs: if model_dict.get(single): single_dict = model_dict.get(single) id_val = single_dict.get('id') cond = {} cond['$or'] = [{'id': id_val}, {'_id': id_val}] modelname = NameFactory.fetch_name(single) Single = classing_model(modelname) item = Single.find_one(appname, cond) if item: single_dict['title'] = item.get('title') model_dict[single] = single_dict return model_dict
def delete_base(cls, appname, model_name, item_id, confirm=False): ''' notice:关联删除,当资源被引用的时候返回DATA_DELETE_COMFIRM, 确认完后如果资源可以被删除,返回1005,不可删除返回1004 return_data format below: { 'status': 0, 'model': {'id':1, 'a':'a', 'b':'b',...} } { 'status': 10, # parameter error 'model': {'id':1, 'a':'a', 'b':'b',...} } { 'status': 1004, # can not be deleted, 'model': {'id':1, 'a':'a', 'b':'b',...} } { 'status': 1005, # can be deleted, but need confirm 'model': {'id':1, 'a':'a', 'b':'b',...} } ''' return_data = {} # track the data deleted for user log Model_Name = classing_model(model_name) # get model class relation = Model_Name.relation parent_list = relation.get("parent") # get the passed in model content and check it legally model = Model_Name.find_one(appname, cond={"id": item_id}) return_data['model'] = model if not model: _LOGGER.error("model %s id %s is not exist", model_name, item_id) return_data.update({'status': PARAM_ERROR}) return return_data # before enter into delete flow, shoud check weather it is refered by # the top model not can not been unrefered, used configuration 'links' if _check_refinfo(appname, item_id, model_name): return_data.update({'status': DATA_RELETED_BY_OTHER}) return return_data # deal with model's parent model, unrefered with the parent model if parent_list: for parent in parent_list: # delete reference from parent tables ret_dict = _unrefered_parents( appname, parent, model_name, item_id, confirm) if ret_dict: return_data.update(ret_dict) return return_data else: _LOGGER.info("%s has no parent model", model_name) # unrefered the icon to the model cls.dec_icon(appname, model_name, model, item_id) Model_Name.remove(appname, {"id": item_id}) return_data.update({'status': OK}) return return_data
def localize_titles(self, locale_titles): ThemeLocale = classing_model('themelocale') locale_dict = {} if locale_titles: lt_ids = [lt.get('id') for lt in locale_titles] title_infos = ThemeLocale.find( self.appname, cond={'id': {'$in': lt_ids}}, fields={'_id': 0}, toarray=True) for title in title_infos: locale_dict[title.get('locale')] = title.get('name') return locale_dict
def get_upload_table(modelname): ''' every model has one map upload collection ''' Model_Class = classing_model(modelname) upload_table = '' if hasattr(Model_Class, "upload_table"): upload_table = Model_Class.upload_table else: upload_table = modelname return upload_table
def refresh_status(appname, modelname, model_id): Model_Class = classing_model(modelname) result_dict = {} new_item = Model_Class.find_one( appname, {'id': model_id}, fields={'_id': 0}) new_item = upload_status(new_item) fields = [ 'id', 'title', 'name', 'last_release_ec2', 'last_release_local', 'release', 'is_upload_local', 'is_upload_ec2'] for field in fields: result_dict[field] = new_item.get(field) return result_dict
def _get_ruleids(appname, search_word, field='lcpn'): rule_ids = [] Rule = classing_model("aosruledata") cond = {} if field == 'lcpn': cond_list = [] Locale = classing_model("aoslocale") Package = classing_model("aospackage") cond_locale = { 'title': {'$regex': re.escape(search_word), '$options': '$i'}} locale_list = Locale.find( appname, cond_locale, fields={'_id': 1}, toarray=True) cond_package = { 'package_name': { '$regex': re.escape(search_word), '$options': '$i'}} package_list = Package.find( appname, cond_package, fields={'_id': 1}, toarray=True) if locale_list: locale_ids = [p.get('_id') for p in locale_list] cond_list.append({"locale": {'$in': locale_ids}}) if package_list: package_ids = [p.get('_id') for p in package_list] cond_list.append({"package": {'$in': package_ids}}) if cond_list: cond['$or'] = cond_list else: return rule_ids elif field == 'rule': cond = { 'title': {'$regex': re.escape(search_word), '$options': '$i'}} else: return rule_ids rule_list = Rule.find( appname, cond, fields={'_id': 1}, toarray=True) if rule_list: rule_ids = [r.get('_id') for r in rule_list] return rule_ids
def fetch_lcpn(cls, appname, rule_dict): ''' ref locale and package when item loads ''' res_dict = {} Ruledata = classing_model("aosruledata") Locale = classing_model("aoslocale") Package = classing_model("aospackage") ruledata = Ruledata.find_one(appname, {"_id": rule_dict.get('id')}) cond_locale = {'_id': {'$in': ruledata.get('locale')}} locale_list = Locale.find( appname, cond_locale, fields={'_id': 0, 'title': 1}, toarray=True) if locale_list: locales = [p.get('title') for p in locale_list] res_dict['locale'] = ','.join(locales) cond_package = {'_id': {'$in': ruledata.get('package')}} package_list = Package.find( appname, cond_package, fields={'_id': 0, 'package_name': 1}, toarray=True) if package_list: packages = [p.get('package_name') for p in package_list] res_dict['package'] = ','.join(packages) return res_dict
def _get_ids(appname, child_ids, child_model, parent_model): ''' 通过子model的id获取父model的id ''' parent_ids = [] cond = {} Parent_Model = classing_model(parent_model) for child_id in child_ids: cond = NameFactory.combine_cond(child_model, child_id) parents = Parent_Model.find( appname, cond, fields={'_id': 0}, toarray=True) if parents: parent_ids = [p.get('id') for p in parents] return list(set(parent_ids))
def get_topmodel_ids(appname, model_id, modelname): ''' passed in the model id, and will return a dict of refered infos, it is passed through attr object_link. ''' Model_Name = classing_model(modelname) res_dict = {} if hasattr(Model_Name, "object_links"): ref_dict = Model_Name.object_links for ref in ref_dict: object_link = ref_dict[ref] topmodel = object_link[-1] top_ids = ref_topmodel(appname, model_id, modelname, object_link) res_dict.setdefault(topmodel, []).extend(top_ids) return res_dict
def check_need_params(modelname, save_dict): ModelClass = classing_model(modelname) fields = ModelClass.fields_check check_success = True msg = 'check need param value' for fld in fields: paras = fld.split('&') (param_key, param_option, param_type, default_value) = tuple( paras) + (None, ) * (4 - len(paras)) if param_option == 'need' and not param_type == 'bool': # need key must has a value, but except bool type if not save_dict.get(param_key): check_success = False msg = '%s should not be empty' % param_key break return check_success, msg
def themefolder_check(self, save_dict): size = save_dict.get('size') isfree = save_dict.get('isfree') themes = save_dict.get('theme') theme_ids = [t.get('id') for t in themes] Theme = classing_model('theme') theme_infos = Theme.find( self.appname, cond={'id': {'$in': theme_ids}}, fields={'_id': 0}, toarray=True) for theme_info in theme_infos: theme_size = theme_info.get('size') theme_free = theme_info.get('isfree') if not size == theme_size or not isfree == theme_free: self.check_success = False self.msg = 'theme %s in folder is not matched size or paid\ type' % theme_info.get('title') break return self.check_success, self.msg
def common_delete(appname, modelname, comfirm, item_ids): success_list = [] data = {} Model_Name = classing_model(modelname) items = Model_Name.find( appname, {'id': {'$in': item_ids}}, fields={'_id': 0}, toarray=True) for item in items: item_id = item.get('id') success_list.append(common_filter(item)) ret = CommonBase.delete_base(appname, modelname, item_id, comfirm) if ret: status = ret.get('status') model_dict = ret.get('model') if status: # none or not zero, return directly success_list.remove(common_filter(model_dict)) data['userlog'] = success_list return json_response_error( status, msg="item has been refered", data=data) data['userlog'] = success_list return json_response_ok(data=data, msg='delete success items')
def online(appname, modelname, item_ids, server): Model_Class = classing_model(modelname) items = Model_Class.find( appname, {'id': {'$in': item_ids}}, fields={'_id': 0}, toarray=True) if not items: return json_response_error(PARAM_ERROR, msg="no item find") results = online_data(appname, modelname, server, items) status = results[0] out_msg = results[1] data = {} data["success"] = results[2] data["failed"] = results[3] data['userlog'] = [common_filter(i) for i in data.get('success')] data['memo'] = 'online to %s' % server if status == -1: return json_response_error(PARAM_ERROR, msg="UNKNOWN UPLOAD SERVER") elif status == 0: return json_response_ok(data, msg="upload successfully") else: return json_response_error(status, data, msg=out_msg)
def check_data_unique(appname, modelname, save_dict, item_id=None): check_success = True msg = 'check unique param value' ModelClass = classing_model(modelname) if not getattr(ModelClass, 'unique', None): return check_success, msg cond = build_unqiue_cond(modelname, save_dict) if not item_id: # insert before check unique item = ModelClass.find_one(appname, cond) if item: check_success = False msg = "insert before, check unique fail" else: item_old = ModelClass.find_one(appname, {'id': item_id}) item_find = ModelClass.find_one(appname, cond) if item_find and not item_find == item_old: check_success = False msg = "update before, check unique fail" return check_success, msg