基于声明式字典的Python模型类
项目描述
# micromodels
一个用于基于数据字典构建模型类的简单库。
非常适合(包括其他方面)将Python对象包装在来自基于Web的API返回的JSON数据中。
**作者**: Jamie Matthews (<https://github.com/j4mie>) 和 Eric Martin (<https://github.com/lightcatcher>).
## 安装
pip安装micromodels
## 真的很简单的示例
import micromodels
class Author(micromodels.Model)
first_name = micromodels.CharField()
last_name = micromodels.CharField()
date_of_birth = micromodels.DateField(format="%Y-%m-%d")
@property
def full_name(self)
return "%s %s" % (self.first_name, self.last_name)
douglas_data = {
"first_name": "Douglas",
"last_name": "Adams",
"date_of_birth": "1952-03-11",
}
douglas = Author.from_dict(douglas_data)
print "%s was born in %s" % (douglas.full_name, douglas.date_of_birth.strftime("%Y"))
## 略微复杂的示例
import json
from urllib2 import urlopen
import micromodels
class TwitterUser(micromodels.Model)
id = micromodels.IntegerField()
screen_name = micromodels.CharField()
name = micromodels.CharField()
description = micromodels.CharField()
def get_profile_url(self)
return 'http://twitter.com/%s' % self.screen_name
class Tweet(micromodels.Model)
id = micromodels.IntegerField()
text = micromodels.CharField()
created_at = micromodels.DateTimeField(format="%a %b %d %H:%M:%S +0000 %Y")
用户 = micromodels.ModelField(TwitterUser)
json_data = urlopen('http://api.twitter.com/1/statuses/show/20.json').read()
tweet = Tweet.from_dict(json_data, is_json=True)
print tweet.user.name
print tweet.user.get_profile_url()
print tweet.id
print tweet.created_at.strftime('%A')
## 模型实例中也可以添加新的字段
## 需要使用方法来处理序列化
tweet.add_field('retweet_count', 44, micromodels.IntegerField())
print tweet.retweet_count
## 数据可以转换为字典(仍包含时间对象)
print tweet.to_dict()
## 也可以转换为JSON(字段处理自己的序列化)
print tweet.to_json()
## tweet.to_json() 等同于以下调用
json.dumps(tweet.to_dict(serial=True))
## 字段参考
### 字段选项
以下可选参数对所有字段类型均可用。
#### `source`
默认情况下,模型类将在其源数据中查找与每个字段同名的键。例如
class ExampleModel(micromodels.Model)
myfield = micromodels.CharField()
>>> e = ExampleModel({'myfield': 'Some Value'})
>>> e.myfield
u'Some Value'
如果您想更改此设置,可以将 'source' 参数传递给每个字段实例
class ExampleModel(micromodels.Model)
myfield = micromodels.CharField()
anotherfield = micromodels.CharField(source='some_other_field')
>>> e = ExampleModel({'myfield': 'Some Value', 'some_other_field': 'Another Value'})
>>> e.anotherfield
u'Another Value'
### 字段类型
#### BaseField
最简单的字段类型 - 这仅仅是将数据字典中的内容原样传递,不进行任何更改。
#### CharField
字符串数据字段。**将尝试将其提供的数据转换为Unicode**。
#### IntegerField
尝试将其提供的数据转换为整数。
#### FloatField
尝试将其提供的数据转换为浮点值。
#### BooleanField
尝试将其提供的数据转换为布尔值。如果数据是字符串,"true"(不区分大小写)将转换为True,其他所有字符串将转换为False。如果提供的数据是整数,正数将变为True,负数或零将变为False。
#### DateTimeField
将其提供的数据转换为Python `datetime.datetime`对象作为`ISO8601`。
class MyModel(micromodels.Model)
created_at = micromodels.DateTimeField()
可以提供可选的格式。
class MyModel(micromodels.Model)
created_at = micromodels.DateTimeField(format="%a %b %d %H:%M:%S +0000 %Y")
有关格式字符串的详细信息,请参阅 [Python
文档](https://docs.pythonlang.cn/library/datetime.html#strftime-strptime-behavior)
例如
#### DateField
将其提供的数据转换为Python `datetime.date`对象作为
`ISO8601`或使用可选的`format`参数(有关详细信息,请参阅`DateTimeField`
)
#### TimeField
将其提供的数据转换为Python `datetime.time`对象作为
`ISO8601`或使用可选的`format`参数(有关详细信息,请参阅`DateTimeField`
)
#### FieldCollectionField
当您的源数据字典包含相同类型的项的列表时,请使用此字段。它接受一个必需参数,即用于转换列表中每个项目的字段类型。例如
some_data = {
'first_list': [0, 34, 42],
}
class MyModel(micromodels.Model)
'second_list': ['first_item', 'second_item', 'third_item'],
first_list = micromodels.FieldCollectionField(micromodels.IntegerField)
second_list = micromodels.FieldCollectionField(micromodels.CharField)
>>> m = MyModel(some_data)
[0, 34, 42]
>>> m.first_list
>>> m.second_list
[u'first_item', u'second_item', u'third_item']
#### ModelField
当您的源数据字典包含相同类型的项的列表时,请使用此字段。它接受一个必需参数,即用于转换列表中每个项目的字段类型。例如
当您希望在另一个对象内部嵌套一个对象时,请使用此字段。它接受一个必需参数,即嵌套类。例如,给定以下字典
'first_item': 'Some value',
'second_item': {
},
}
'nested_item': 'Some nested value',
您可以构建以下类(请注意,您必须首先定义嵌套的模型)
class MyNestedModel(micromodels.Model)
nested_item = micromodels.CharField()
class MyMainModel(micromodels.Model)
second_item = micromodels.ModelField(MyNestedModel) # 传递嵌套模型的类
然后你可以按以下方式访问数据
>>> m = MyMainModel(some_data)
>>> m.first_item
u'Some value'
>>> m.second_item.__class__.__name__
'MyNestedModel'
>>> m.second_item.nested_item
u'Some nested value'
#### ModelCollectionField
当你的源数据字典包含字典列表时,请使用此字段。它需要一个必需的参数,即列表中每个项目应转换为的嵌套类的名称。例如
当您的源数据字典包含相同类型的项的列表时,请使用此字段。它接受一个必需参数,即用于转换列表中每个项目的字段类型。例如
'list': [
{'value': 'First value'},
{'value': 'Second value'},
{'value': 'Third value'},
]
}
您可以构建以下类(请注意,您必须首先定义嵌套的模型)
value = micromodels.CharField()
nested_item = micromodels.CharField()
list = micromodels.ModelCollectionField(MyNestedModel)
>>> m = MyMainModel(some_data)
>>> len(m.list)
3
>>> m.list[0].__class__.__name__
'MyNestedModel'
>>> m.list[0].value
u'First value'
>>> [item.value for item in m.list]
[u'First value', u'Second value', u'Third value']
## (Un)license
这是一款免费且不受限制的软件,已发布到公有领域。
任何人都可以免费复制、修改、发布、使用、编译、销售或分发此软件,无论是源代码形式还是编译的二进制形式,出于任何目的,商业或非商业,以及任何方式。
在承认版权法的司法管辖区,此软件的作者或作者将此软件的任何和所有版权利益奉献给公有领域。我们做出此奉献是为了公众的大局利益,以及牺牲我们的继承人及其继任者的利益。我们意图此奉献是一项永久放弃根据版权法对软件的现有和未来所有权利的明确行为。
软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、适用于特定目的和非侵权性保证。在任何情况下,作者不对任何索赔、损害或其他责任负责,无论这些责任源于合同、侵权或其他方式,是否与软件或其使用或其他方式有关。
有关更多信息,请参阅 <http://unlicense.org/>
一个用于基于数据字典构建模型类的简单库。
非常适合(包括其他方面)将Python对象包装在来自基于Web的API返回的JSON数据中。
**作者**: Jamie Matthews (<https://github.com/j4mie>) 和 Eric Martin (<https://github.com/lightcatcher>).
## 安装
pip安装micromodels
## 真的很简单的示例
import micromodels
class Author(micromodels.Model)
first_name = micromodels.CharField()
last_name = micromodels.CharField()
date_of_birth = micromodels.DateField(format="%Y-%m-%d")
@property
def full_name(self)
return "%s %s" % (self.first_name, self.last_name)
douglas_data = {
"first_name": "Douglas",
"last_name": "Adams",
"date_of_birth": "1952-03-11",
}
douglas = Author.from_dict(douglas_data)
print "%s was born in %s" % (douglas.full_name, douglas.date_of_birth.strftime("%Y"))
## 略微复杂的示例
import json
from urllib2 import urlopen
import micromodels
class TwitterUser(micromodels.Model)
id = micromodels.IntegerField()
screen_name = micromodels.CharField()
name = micromodels.CharField()
description = micromodels.CharField()
def get_profile_url(self)
return 'http://twitter.com/%s' % self.screen_name
class Tweet(micromodels.Model)
id = micromodels.IntegerField()
text = micromodels.CharField()
created_at = micromodels.DateTimeField(format="%a %b %d %H:%M:%S +0000 %Y")
用户 = micromodels.ModelField(TwitterUser)
json_data = urlopen('http://api.twitter.com/1/statuses/show/20.json').read()
tweet = Tweet.from_dict(json_data, is_json=True)
print tweet.user.name
print tweet.user.get_profile_url()
print tweet.id
print tweet.created_at.strftime('%A')
## 模型实例中也可以添加新的字段
## 需要使用方法来处理序列化
tweet.add_field('retweet_count', 44, micromodels.IntegerField())
print tweet.retweet_count
## 数据可以转换为字典(仍包含时间对象)
print tweet.to_dict()
## 也可以转换为JSON(字段处理自己的序列化)
print tweet.to_json()
## tweet.to_json() 等同于以下调用
json.dumps(tweet.to_dict(serial=True))
## 字段参考
### 字段选项
以下可选参数对所有字段类型均可用。
#### `source`
默认情况下,模型类将在其源数据中查找与每个字段同名的键。例如
class ExampleModel(micromodels.Model)
myfield = micromodels.CharField()
>>> e = ExampleModel({'myfield': 'Some Value'})
>>> e.myfield
u'Some Value'
如果您想更改此设置,可以将 'source' 参数传递给每个字段实例
class ExampleModel(micromodels.Model)
myfield = micromodels.CharField()
anotherfield = micromodels.CharField(source='some_other_field')
>>> e = ExampleModel({'myfield': 'Some Value', 'some_other_field': 'Another Value'})
>>> e.anotherfield
u'Another Value'
### 字段类型
#### BaseField
最简单的字段类型 - 这仅仅是将数据字典中的内容原样传递,不进行任何更改。
#### CharField
字符串数据字段。**将尝试将其提供的数据转换为Unicode**。
#### IntegerField
尝试将其提供的数据转换为整数。
#### FloatField
尝试将其提供的数据转换为浮点值。
#### BooleanField
尝试将其提供的数据转换为布尔值。如果数据是字符串,"true"(不区分大小写)将转换为True,其他所有字符串将转换为False。如果提供的数据是整数,正数将变为True,负数或零将变为False。
#### DateTimeField
将其提供的数据转换为Python `datetime.datetime`对象作为`ISO8601`。
class MyModel(micromodels.Model)
created_at = micromodels.DateTimeField()
可以提供可选的格式。
class MyModel(micromodels.Model)
created_at = micromodels.DateTimeField(format="%a %b %d %H:%M:%S +0000 %Y")
有关格式字符串的详细信息,请参阅 [Python
文档](https://docs.pythonlang.cn/library/datetime.html#strftime-strptime-behavior)
例如
#### DateField
将其提供的数据转换为Python `datetime.date`对象作为
`ISO8601`或使用可选的`format`参数(有关详细信息,请参阅`DateTimeField`
)
#### TimeField
将其提供的数据转换为Python `datetime.time`对象作为
`ISO8601`或使用可选的`format`参数(有关详细信息,请参阅`DateTimeField`
)
#### FieldCollectionField
当您的源数据字典包含相同类型的项的列表时,请使用此字段。它接受一个必需参数,即用于转换列表中每个项目的字段类型。例如
some_data = {
'first_list': [0, 34, 42],
}
class MyModel(micromodels.Model)
'second_list': ['first_item', 'second_item', 'third_item'],
first_list = micromodels.FieldCollectionField(micromodels.IntegerField)
second_list = micromodels.FieldCollectionField(micromodels.CharField)
>>> m = MyModel(some_data)
[0, 34, 42]
>>> m.first_list
>>> m.second_list
[u'first_item', u'second_item', u'third_item']
#### ModelField
当您的源数据字典包含相同类型的项的列表时,请使用此字段。它接受一个必需参数,即用于转换列表中每个项目的字段类型。例如
当您希望在另一个对象内部嵌套一个对象时,请使用此字段。它接受一个必需参数,即嵌套类。例如,给定以下字典
'first_item': 'Some value',
'second_item': {
},
}
'nested_item': 'Some nested value',
您可以构建以下类(请注意,您必须首先定义嵌套的模型)
class MyNestedModel(micromodels.Model)
nested_item = micromodels.CharField()
class MyMainModel(micromodels.Model)
second_item = micromodels.ModelField(MyNestedModel) # 传递嵌套模型的类
然后你可以按以下方式访问数据
>>> m = MyMainModel(some_data)
>>> m.first_item
u'Some value'
>>> m.second_item.__class__.__name__
'MyNestedModel'
>>> m.second_item.nested_item
u'Some nested value'
#### ModelCollectionField
当你的源数据字典包含字典列表时,请使用此字段。它需要一个必需的参数,即列表中每个项目应转换为的嵌套类的名称。例如
当您的源数据字典包含相同类型的项的列表时,请使用此字段。它接受一个必需参数,即用于转换列表中每个项目的字段类型。例如
'list': [
{'value': 'First value'},
{'value': 'Second value'},
{'value': 'Third value'},
]
}
您可以构建以下类(请注意,您必须首先定义嵌套的模型)
value = micromodels.CharField()
nested_item = micromodels.CharField()
list = micromodels.ModelCollectionField(MyNestedModel)
>>> m = MyMainModel(some_data)
>>> len(m.list)
3
>>> m.list[0].__class__.__name__
'MyNestedModel'
>>> m.list[0].value
u'First value'
>>> [item.value for item in m.list]
[u'First value', u'Second value', u'Third value']
## (Un)license
这是一款免费且不受限制的软件,已发布到公有领域。
任何人都可以免费复制、修改、发布、使用、编译、销售或分发此软件,无论是源代码形式还是编译的二进制形式,出于任何目的,商业或非商业,以及任何方式。
在承认版权法的司法管辖区,此软件的作者或作者将此软件的任何和所有版权利益奉献给公有领域。我们做出此奉献是为了公众的大局利益,以及牺牲我们的继承人及其继任者的利益。我们意图此奉献是一项永久放弃根据版权法对软件的现有和未来所有权利的明确行为。
软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、适用于特定目的和非侵权性保证。在任何情况下,作者不对任何索赔、损害或其他责任负责,无论这些责任源于合同、侵权或其他方式,是否与软件或其使用或其他方式有关。
有关更多信息,请参阅 <http://unlicense.org/>
项目详情
关闭
micromodels-0.5.1.tar.gz 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | e2a6f3388c9583ea04da6c1072906227017d3d221bf75fd182b6cf9557d440a7 |
|
MD5 | 9e96d424212015a6952737be7cb8d512 |
|
BLAKE2b-256 | 492968076e9abf6fe28e8202a467c5a217687999fda57dac51817cb0ae1aef7a |