Franz Noel Franz Noel - 2 months ago 8
Python Question

Convert a string to another Python class

Is there anyway to create another class for a Model?

For example, I have model.py, 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
dir(model)
, 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
dir(model)
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"
self.response.write(json.dumps(customers))


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...

Answer

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"
    self.response.write(json.dumps(customers))

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.