有没有办法为模型创建另一个类?
比如我有model.py,里面的类包含:
class Customers(ndb.Model):
lastname = ndb.StringProperty()
firstname = ndb.StringProperty()
license = ndb.StringProperty()
birthdate = ndb.DateProperty()
remarks = ndb.TextProperty()
我知道我可以使用 dir(model)
获取模型,它输出如下内容:
['Customers', 'CustomerAddresses','Whatever','__builtins__', '__doc__', '__file__', '__name__', '__package__', 'ndb']
但是,有什么方法可以在 dir(model)
中使用这些字符串来自动生成另一个类,例如:
class RestCustomers(webapp2.RequestHandler):
#some code that gets the model class attributes and displays the json string
customers = # customer attributes from model
self.response.headers['Content-Type'] = "application/json"
self.response.write(json.dumps(customers))
我不确定这是否可能,但有点像 javascript 的工作方式,你会说这样的话
var models = dir(models); // which is an array
var class = "Rest"+models[0];
或者类似的东西...
最佳答案
尝试这样的事情:
from google.appengine.ext.ndb import metadata
class RestCustomers(webapp2.RequestHandler):
customers = metadata.get_properties_of_kind(Customers)
self.response.headers['Content-Type'] = "application/json"
self.response.write(json.dumps(customers))
有关详细信息,请参阅documentation about metadata 。我不完全确定 get_properties_of_kind
期望如何获取 kind
参数,所以尝试一下。
关于python - 将字符串转换为另一个 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18491061/