I'm working on a Google App Engine project using Python and MySqlDB, and the App Engine requires me to return a Message object to the endpoint.
This is how the returning class looks:
class ReturningClass(messages.Message):
"""Return Column values stored here."""
ID = messages.IntegerField(1)
Locality_Name = messages.StringField(2)
Pincode = messages.IntegerField(3)
No_of_LL = messages.IntegerField(4)
No_of_Hospitals = messages.IntegerField(5)
No_of_Hotels = messages.IntegerField(6)
And So on...
There's around 30 columns that I want to fetch dynamically.
This below is a Collection of the ReturningClass
class ReturningClassCollection(messages.Message):
"""Collection of ReturningClass objects."""
items = messages.MessageField(ReturningClass, 1, repeated=True)
And this is the Main Class that actually does all the returning:
class MainClass(webapp2.RequestHandler):
def get(self,Columns):
if (os.getenv('SERVER_SOFTWARE') and
os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/')):
db = MySQLdb.connect(unix_socket='/cloudsql/' + _INSTANCE_NAME, db='DatabaseName', user='root')
else:
db = MySQLdb.connect(host='127.0.0.1', port=3306, db='DatabaseName', user='root')
cursor = db.cursor()
ReturningArray=ReturningClassCollection()
query="SELECT %s FROM DemoTable"%(Columns)
cursor.execute(query)
for result in cursor.fetchall():
ReturningArray.items.append(ReturningClass(
ID = result[0] ,
Locality_Name = cgi.escape(result[1]),
Pincode = result[2],
No_of_LL= result[3],
No_of_Hospitals = result[4]
))
cursor.close()
db.close()
return ReturningArray
This works if I give the select statement the 5 expected column values that are hard coded into the returning cursor.
Ex:
query="SELECT ID,Locality_Name,Pincode,No_of_LL,No_of_Hospitals,No_of_Hotels
FROM DemoTable"
But if I do:
query="SELECT ID,Locality_Name
FROM DemoTable"
I get a:
IndexError: tuple index out of range
How do I get the
for result in cursor.fetchall():
ReturningArray.items.append(ReturningClass(
??
))
to return only the columns that are in the select statement?