本文介绍了如何将google app引擎的ndb属性子类化为支持python子类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从本文

我有一个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对象中使用这个属性来添加学校名称作为密码和权限为dict值, ex(用户可以在多个学校获得权限):

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.....

我试图关注这个doc
没有利润!

I've tried to follow this doc https://cloud.google.com/appengine/docs/python/ndb/subclasspropwith no profit !

甚至有可能吗?如果是,怎么样?
谢谢...

so is it even possible ? and if so, how ?thank you...

推荐答案

App Engine的ndb包不支持直接保存字典,但json可以保存在一个 JsonProperty 中,字典很容易编码为json,所以最简单的实现是 JsonProperty 的子类,返回一个权限访问实例

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引擎的ndb属性子类化为支持python子类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:42