如何子类化 Google App Engine ndb 属性以支持 python 子类化对象 [英] how to subclass google app engine ndb property to support python subclassed objects
问题描述
来自这篇文章https://stackoverflow.com/a/32107024/5258689
我有一个 dict() 子类——它允许我做 dict.key(使用点来访问我的意思是)——如下:
I have a dict() subclass - that allows me to do dict.key (use dot to access keys i mean) - as follows:
class Permissions(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Permissions, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v
if kwargs:
for k, v in kwargs.iteritems():
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Permissions, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Permissions, self).__delitem__(key)
del self.__dict__[key]
我的问题是如何创建我自己的PermessionsPropery()?或者要扩展什么属性以便我可以创建它?
my question is how to create my own PermessionsPropery() ? or what property to extend so I can create that ?
我愿意在我的子类 User 对象中使用这个属性来添加学校名称作为键和权限作为字典值,例如(用户可以在多个学校拥有权限):
I am willing to use this property in my subclassed User object to add school name as key and permission as dict value, ex(user can have permissions in multiple schools):
from webapp2_extras.appengine.auth.models import User as webapp2User
class User(webapp2User):
permissions = PermissionsProperty()
u = User(permissions=Permissions({"school1": {"teacher": True}}))
然后我检查用户的权限,例如:
then I check for user's permissions like:
if user.permissions[someshcool].teacher:
#do stuff.....
#or
if user.permissions.someschool.teacher:
#do stuff.....
我尝试遵循此文档 https://cloud.google.com/appengine/docs/python/ndb/subclassprop没有利润!
I've tried to follow this doc https://cloud.google.com/appengine/docs/python/ndb/subclassprop with no profit !
所以有可能吗?如果是这样,如何?谢谢...
so is it even possible ? and if so, how ? thank you...
推荐答案
App Engine的ndb包不支持直接保存字典,但是json可以保存在JsonProperty
中,字典很容易编码作为 json,所以最简单的实现是 JsonProperty
的子类,它在访问时返回一个 Permissions
实例.
App Engine's ndb package doesn't support saving dictionaries directly, but json can be saved in a JsonProperty
, and dictionaries are easily encoded as json, so the simplest implementation is a subclass of JsonProperty
that returns a Permissions
instance when accessed.
class PermissionsProperty(ndb.JsonProperty):
def _to_base_type(self, value):
return dict(value)
def _from_base_type(self, value):
return Permissions(value)
虽然这个实现是不完整的,因为 JsonProperty 会接受不是 Permissions 实例的值,所以你需要添加一个 _validate
方法来确保你保存的是正确类型的对象.
This implementation is incomplete though, because JsonProperty will accept values that aren't Permissions instances, so you need to add a _validate
method to ensure that what you're saving is the right type of object.
class PermissionsProperty(ndb.JsonProperty):
def _to_base_type(self, value):
return dict(value)
def _from_base_type(self, value):
return Permissions(value)
def _validate(self, value):
if not isinstance(value, Permissions):
raise TypeError('Expected Permissions instance, got %r', % value)
这篇关于如何子类化 Google App Engine ndb 属性以支持 python 子类化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!