允许 StringField 强制最大长度¶
https://blueprints.launchpad.net/nova/+spec/string-field-max-length
此蓝图旨在为 nova.objects.fields.StringField 类添加最大长度约束。
问题描述¶
目前,nova 对象框架围绕着使用字段类型类来描述对象的模式。每个对象模型只是字段的集合,每个字段都有特定的类型,例如 IntegerField 或 StringField。
就像 SQL 数据库模式描述了表中给定列必须遵守的约束——例如,CHAR 字段中可能的字符长度,或有效的 DATETIME 字符串——nova 对象应该能够自我验证。
提议的变更¶
本规范建议更改 String 类的 coerce 方法,以验证字段字符串值的字符数。
具体的 StringField 字段类将向其构造函数添加一个新的 max_length 关键字参数,该参数将控制验证。默认值为 None,并且本规范不会更改 nova 对象模型模式中定义的任何 StringField 对象。
备选方案¶
无 (保持现状)
数据模型影响¶
无 (现有模型本身不会在此规范中进行任何更改)
REST API 影响¶
无
安全影响¶
无
通知影响¶
无
其他最终用户影响¶
无
性能影响¶
无
其他部署者影响¶
无
开发人员影响¶
无
实现¶
大致来说,String 字段类型类的代码将从以下代码更改为
class String(FieldType):
@staticmethod
def coerce(obj, attr, value):
# FIXME(danms): We should really try to avoid the need to do this
if isinstance(value, (six.string_types, int, long, float,
datetime.datetime)):
return unicode(value)
else:
raise ValueError(_('A string is required here, not %s') %
value.__class__.__name__)
更改为以下代码
class String(FieldType):
def __init__(self, max_length=None):
"""
:param max_length: Optional constraint on the number of Unicode
characters the string value can be.
"""
self._max_length = max_length
@staticmethod
def coerce(self, obj, attr, value):
# FIXME(danms): We should really try to avoid the need to do this
if isinstance(value, (six.string_types, int, long, float,
datetime.datetime)):
result = unicode(value)
else:
raise ValueError(_('A string is required here, not %s') %
value.__class__.__name__)
if self._max_length is not None:
if len(value) > self._max_length):
msg = _("String %(result)s is longer than maximum allowed "
"length of %(max_length)d.")
msg = msg % dict(result=result,
max_length=self._max_length)
raise ValueError(msg)
return result
然后需要修改 StringField 类,以允许将 max_length 参数传递给其类型类。
工作项¶
N/A
负责人¶
- 主要负责人
jaypipes
依赖项¶
无
测试¶
需要新的单元测试。不需要任何集成测试更改。
文档影响¶
无
参考资料¶
服务器实例标记工作很可能会最先使用此功能,因为标签字符串具有最大长度限制,并且我们需要非常小心地更改现有模型字段的字符串长度验证代码,因此像标签字段这样的新字段是开始此实现的一个理想场所。
http://git.openstack.org/cgit/openstack/nova-specs/tree/specs/juno/tag-instances.rst