不要存储类本身,存储导入路径作为数据库中的字符串(如“django.forms.CharField”)
我开始做同样的事情了另一个项目,并保存关闭代码在我的本地存储库中。为了解决安全问题,我打算为允许的基类的字段构造函数添加一个参数。如果你确实实现了这一点,请告诉我,我很乐意收到。
helpers.py
def get_class_from_concrete_classpath(class_path):
# Unicode will throw errors in the __import__ (at least in 2.6)
class_path = str(class_path)
mod_list = class_path.split('.')
module_path = '.'.join(mod_list[:-1])
class_name = mod_list[-1]
base_mod = __import__(module_path, fromlist=[class_name,])
return getattr(base_mod, class_name)
def get_concrete_name_of_class(klass):
"""Given a class return the concrete name of the class.
klass - The reference to the class we're interested in.
Raises a `TypeError` if klass is not a class.
"""
if not isinstance(klass, (type, ClassType)):
raise TypeError('The klass argument must be a class. Got type %s; %s' %
(type(klass), klass))
return '%s.%s' % (klass.__module__, klass.__name__)
fields.py
class ClassFormField(forms.Field):
def to_python(self, value):
return get_concrete_name_of_class(value)
class ClassField(models.CharField):
__metaclass__ = models.SubfieldBase
"""Field used for storing a class as a string for later retrieval"""
MAX_LENGTH = 255
default_error_messages = {
'invalid': _(u'Enter a valid class variable.'),
}
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', ClassField.MAX_LENGTH)
super(ClassField, self).__init__(*args, **kwargs)
def get_prep_value(self, value):
if isinstance(value, (basestring, NoneType)):
return value
return get_concrete_name_of_class(value)
def to_python(self, value):
if isinstance(value, basestring):
return get_class_from_concrete_classpath(value)
return value
def formfield(self, **kwargs):
defaults = {'form_class' : ClassFormField}
defaults.update(kwargs)
return super(ClassField, self).formfield(**defaults)
如果__you__放在数据库中的类有一个'__init__'没关系。总的来说,__attacker__可以将一些其他类放在数据库中,__does__有一个'__init__'。另外'__init__'是一个红鲱鱼。它也可以覆盖模型的'save'或'clean'方法。 – aaronasterling 2010-09-18 20:33:10
我明白,在实例化之前验证从数据库中获取的任何类是可能的,但这可能不值得麻烦,您可以解析文件并确保它符合某些标准等,但我认为其他方法vasil暗示会更好 – Rick 2010-09-19 07:14:54