有谁知道在 Google App Engine 中返回一个包装的模型实例的巧妙方法,该实例仅公开一些原始属性,并且不允许将实例保存回数据存储区?
我并不是在寻找实际执行这些规则的方法,显然仍然可以通过挖掘其 __dict__
等来更改实例。我只是想要一种避免意外暴露的方法/更改数据。
我最初的想法是这样做(我想为 User
模型的公共(public)版本执行此操作):
class PublicUser(db.Model):
display_name = db.StringProperty()
@classmethod
def kind(cls):
return 'User'
def put(self):
raise SomeError()
不幸的是,GAE 很早就将类型映射到类,因此如果我执行 PublicUser.get_by_id(1)
我实际上会得到一个 User
实例,而不是一个PublicUser
实例。
另外,这个想法是它应该至少看起来是一个Model
实例,这样我就可以将它传递给不知道以下事实的代码:这是一个“简化”版本。最终我想这样做,以便我可以在只读版本上使用我的通用数据公开函数,以便它们仅公开有关用户的公共(public)信息。
更新
我采用了 icio 的解决方案。以下是我编写的用于将属性从 User
实例复制到 PublicUser
实例的代码:
class User(db.Model):
# ...
# code
# ...
def as_public(self):
"""Returns a PublicUser version of this object.
"""
props = self.properties()
pu = PublicUser()
for prop in pu.properties().values():
# Only copy properties that exist for both the PublicUser model and
# the User model.
if prop.name in props:
# This line of code sets the property of the PublicUser
# instance to the value of the same property on the User
# instance.
prop.__set__(pu, props[prop.name].__get__(self, type(self)))
return pu
如果这不是一个好的方法,请发表评论。
最佳答案
您不能在 User
类中创建一个方法来实例化 ReadOnlyUser
对象并根据需要复制成员变量的值吗?您的调用类似于 User.get_by_id(1).readonly()
,其中 readonly
方法按以下形式定义:
class User(db.Model):
def readonly(self):
return ReadOnlyUser(self.name, self.id);
或者您可以让您的 User
类使用方法扩展另一个类,以根据一些静态变量列出要复制的属性或其他内容自动执行此操作。
P.S.我不使用 Python 编写代码
关于python - 在 GAE 中公开模型的 "dumbed-down"只读实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2754721/