python - 将字符串转换为另一个 Python 类

标签 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(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/

相关文章:

java - 如何检查memcache是​​否过期

google-app-engine - 批量排队 Google Cloud 任务

python - 使用 PEX 打包要求和本地模块

python - celery 取消自己

java - 如何优雅地以各种顺序调用方法?

python - Flask 用户管理 : How to make Stateless Server using better authentication ways?

java - 如何阻止 Payara 中的字符串被解释为日期时间?

python - 哪个Django模板布局更好?

php - Twilio Rest API 调用帮助..

java - 使用 GWT 时不相关的 Google App Engine API?