将字符串转换为另一个Python类
是否仍然需要为模型创建另一个类 例如,我有model.py,其中一个类包含:将字符串转换为另一个Python类,python,rest,google-app-engine,google-cloud-datastore,Python,Rest,Google App Engine,Google Cloud Datastore,是否仍然需要为模型创建另一个类 例如,我有model.py,其中一个类包含: class Customers(ndb.Model): lastname = ndb.StringProperty() firstname = ndb.StringProperty() license = ndb.StringProperty() birthdate = ndb.DateProperty() remarks = ndb.TextProperty() 我知道我可以使用dir(mode
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];
或者类似的…您可以使用:
self.__setattr__(variable_name, value)
…试试这样的。虽然我不确定你到底想要什么。我认为你不知道你想要什么;)通常,如果你不得不把这样的东西拼凑在一起,你的想法/设计是不正确的
class NewClass:
def __init__(self, inherits):
for k, v in inherits.__dict__.items():
self.__setattr__(k, v)
试着这样做:
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))
有关更多信息,请参阅。我不完全确定get\u properties\u of \u kind
希望如何获得kind
参数,所以请尝试一下