Franz Noel Franz Noel - 4 months ago 12
Python Question

Convert a string to another Python class

Is there anyway to create another class for a Model?

For example, I have, which one of the class inside contains:

class Customers(ndb.Model):
lastname = ndb.StringProperty()
firstname = ndb.StringProperty()
license = ndb.StringProperty()
birthdate = ndb.DateProperty()
remarks = ndb.TextProperty()

I know I can get the models using
, and it outputs something like:

['Customers', 'CustomerAddresses','Whatever','__builtins__', '__doc__', '__file__', '__name__', '__package__', 'ndb']

However, is there any way that I can use these string inside
to automatically generate another class, like:

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"

I'm not sure if it is possible, but kind of like the way javascript works, wherein you say something like

var models = dir(models); // which is an array
var class = "Rest"+models[0];

or something like that...


Try something like this:

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"

For more information, see the documentation about metadata. I am not completely sure how get_properties_of_kind expects to get the kind argument so try it out.