这两个函数联合起来用在接口返回 json 数据上非常好使。
lang:pythonimport datetimefrom copy import deepcopydef model2dict(model, datetime_format='%Y-%m-%d %H:%M:%S'): """ 本函数用于使对象可 json 序列化,且返回的字典都是新的(deepcopy) """ if isinstance(model, dict): model = Storage(deepcopy(model)) to_pop = [] for k in model: # 过滤 if isinstance(k, basestring) and (k.startswith('_') or k.isupper()): to_pop.append(k) continue # 转换 elif isinstance(model[k], datetime.datetime): model[k] = model[k].strftime(datetime_format) # 递归 else: model[k] = model2dict(model[k], datetime_format) for k in to_pop: model.pop(k) return model elif hasattr(model, '__dict__'): return model2dict(model.__dict__, datetime_format) elif isinstance(model, (list, tuple)): return [model2dict(m, datetime_format) for m in model] else: return modeldef dict_project(data, map_rulls={}): """ 字典投影,支持取 data 的子集和改名。只想投影而不想改名的,写个 1 就行,eg: >>> data {'a': 1, 'b': 2, 'c': 3} >>> map_rulls {'a': 'x', 'c': 1} >>> dict_project(data, map_rulls) {'x': 1, 'c': 3} """ if isinstance(data, dict): data = Storage({map_rulls[k] if isinstance(map_rulls[k], basestring) else k: data[k] for k in data if k in map_rulls}) elif isinstance(data, (list, tuple)): return [dict_project(o) for o in data] else: raise ValueError('无法处理对象: %s' % str(data)) return data
Storage 参见上一篇