您的位置:首页 > 移动开发

app-engine-patch中的to_json_data详解

2009-06-06 03:34 169 查看
app-engine-patch是为了更好的在gae上使用django而写的一些扩展和一些帮助你更轻松的在gae上写代码的辅助函数。

其中ragendja.dbutils是对gae的数据库方面的一些辅助函数模块。

to_json_data(entity_or_list, property_or_properies)是一个将gae中的实例转为json数据的函数。

to_json_data函数返回一个python dict类型的值,你可以再返回了之后再进行一些数据修改工作,然后把这个返回值传给simplejson.dump()或者JSONResponse(也是ragendia.dbutils模块的一个函数)以下是个小例子,没有测试过。

class Person(db.Model):
name = db.StringProperty()
class Cat(db.Model):
owner = db.ReferenceProperty(Person, collection_name="cats")
nickname = db.StringProperty()
# 假设数据已经存入bigTable
person = Person.all().get()
cat = Cat.all().filter("owner = ", person).get()  # 这里注意"owner ="这个空格是一定要的。
# 把cat的数据转成json数据输出
cat_json_data = to_json_data(cat, ['owner.name', 'nickname'])
# 这里还可以修改得到的数据
cat_json_data["nickname"] = "another nickname"
# 输出json
return JSONResponse(cat_json_data)


to_json_data源码:

def to_json_data(model_instance, property_list):
"""
Converts a models into dicts for use with JSONResponse.
You can either pass a single model instance and get a single dict
or a list of models and get a list of dicts.
For security reasons only the properties in the property_list will get
added. If the value of the property has a json_data function its result
will be added, instead.
"""
if hasattr(model_instance, '__iter__'):
return [to_json_data(item, property_list) for item in model_instance]
json_data = {}
for property in property_list:
property_instance = None
try:
property_instance = getattr(model_instance.__class__,
property.split('.', 1)[0])
except:
pass
key_access = property[len(property.split('.', 1)[0]):]
if isinstance(property_instance, db.ReferenceProperty) and /
key_access in ('.key', '.key.name'):
key = property_instance.get_value_for_datastore(model_instance)
if key_access == '.key':
json_data[property] = str(key)
else:
json_data[property] = key.name()
continue
value = getattr_by_path(model_instance, property, None)
value = getattr_by_path(value, 'json_data', value)
json_data[property] = value
return json_data


to_json_data中最后getattr_by_path函数源码:

def getattr_by_path(obj, attr, *default):
"""Like getattr(), but can go down a hierarchy like 'attr.subattr'"""
value = obj
for part in attr.split('.'):
if not hasattr(value, part) and len(default):
return default[0]
value = getattr(value, part)
if callable(value):
value = value()
return value
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐