Skip to content

Commit

Permalink
add type to Field
Browse files Browse the repository at this point in the history
  • Loading branch information
jadbin committed Jul 18, 2018
1 parent 04f2e7c commit e9e219a
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ New features
~~~~~~~~~~~~

- 新增 ``request_ignored`` 事件
- Field添加 ``type`` 参数,表示该字段的类型,在获取该字段的值时会进行类型转换

0.10.1 (2018-07-18)
-------------------
Expand Down
22 changes: 22 additions & 0 deletions tests/test_item.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,25 @@ def test_item():
assert item['f2'] == 'new_v2'
repr_str = repr(item)
assert repr_str == "{'f1': 'v1', 'f2': 'new_v2'}" or repr_str == "{'f2': 'new_v2', 'f1': 'v1'}"


class FieldTypeItem(Item):
none_field = Field()
str_field = Field(type='str')
int_field = Field(type='int')
float_field = Field(type='float')
bool_field = Field(type='bool')
func_field = Field(type=int)
error_field = Field(type='error type')


def test_field_type():
item = FieldTypeItem(str_field=1, int_field='1', float_field='1', bool_field='1', func_field='1', error_field='1')
assert item['none_field'] is None
assert item['str_field'] == '1'
assert isinstance(item['int_field'], int) and item['int_field'] == 1
assert isinstance(item['float_field'], float) and item['float_field'] == 1
assert item['bool_field'] is True
assert isinstance(item['func_field'], int) and item['func_field'] == 1
with pytest.raises(ValueError):
print(item['error_field'])
20 changes: 19 additions & 1 deletion xpaw/item.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from collections import MutableMapping

from . import config


class BaseItem:
"""
Expand Down Expand Up @@ -29,7 +31,23 @@ def __init__(self, **kwargs):
def __getitem__(self, key):
if key not in self:
return None
return self.values[key]
v = self.values[key]
t = self.fields[key].get('type')
if t:
if isinstance(t, str):
if t == 'str':
v = str(v)
elif t == 'int':
v = config.getint(v)
elif t == 'float':
v = config.getfloat(v)
elif t == 'bool':
v = config.getbool(v)
else:
raise ValueError('Unsupported item filed type: {}'.format(t))
else:
v = t(v)
return v

def __contains__(self, name):
return name in self.values
Expand Down

0 comments on commit e9e219a

Please sign in to comment.