我有一个数据模型,它有一些基本属性和数组类型属性,如下所示:
class WordCollection:
"""First model"""
def __init__(self, **properties):
self.name = ""
self.status = CommonStatus.active
self.expire_time = time.time() + 1000 * 60 * 24 # after 1 day
self.created_date = time.time()
self.words = []
self.__dict__.update(properties)
这是一种恶作剧。例如,当我用一个不属于类的属性构造类时,它很容易被黑客攻击
collection = WordCollection(**{..., "hack_property":"large text or irrelative data"})
因此,我使用了类初始化方法:
class WordCollection:
"""Second model"""
def __init__(self, **properties):
self.name = properties["name"] if "name" in properties else ""
self.status = properties["active"] if "active" in properties else CommonStatus.active
self.expire_time = properties["expire_time"] if "expire_time" in properties else time.time() + 1000 * 60 * 24 # after 1 day
self.created_date = properties["created_date"] if "created_date" in properties else time.time()
self.words = properties["words"] if "words" in properties else []
但上述代码并不能完全解决问题:
collection = WordCollection(**{..., "name":{"hack_property":"large text or irrelative data"}})
这是最后重建的代码:
class WordCollection:
"""Third Model"""
def __init__(self, **properties):
self.name = properties["name"] if "name" in properties and isinstance(properties["name"], str) else ""
self.status = properties["active"] if "active" in properties \
and isinstance(properties["status"], int) else CommonStatus.active
....
上述修订解决了我的问题,但它带来了条件复杂性,我相信这将是比上述更好的解决方案
更标准的配方:
相关问题 更多 >
编程相关推荐