返回Collection类时,元组索引超出范围

时间:2015-03-16 08:37:24

标签: python mysql-python google-app-engine-python

我正在使用Python和MySqlDB处理Google App Engine项目,而App Engine要求我将Message对象返回到端点。
这就是返回类的外观:

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

我想要动态获取大约30列。

以下是ReturningClass的集合

class ReturningClassCollection(messages.Message):
    """Collection of ReturningClass objects."""
    items = messages.MessageField(ReturningClass, 1, repeated=True)

这是实际完成所有返回的主类:

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

如果我将select语句的5个预期列值硬编码到返回的游标中,这是有效的 例如:

query="SELECT ID,Locality_Name,Pincode,No_of_LL,No_of_Hospitals,No_of_Hotels 
FROM DemoTable"

但如果我这样做:

query="SELECT ID,Locality_Name  
FROM DemoTable"

我得到了:

IndexError: tuple index out of range

我如何获得

for result in cursor.fetchall():
     ReturningArray.items.append(ReturningClass(
     ??
     ))

只返回select语句中的列?

1 个答案:

答案 0 :(得分:3)

你的问题不是很清楚。显然,您无法通过您尚未从数据库中获取的列。

如果您实际上询问如何动态传递您选择的任何列到消息类中,您可以使用字典光标并将该dict传递到消息实例化中:

from MySQL import cursors
...
cursor = db.cursor(cursors.DictCursor)
...
for result in cursor.fetchall():
    returning_obj = ReturningClass(**result)
    returning_array.append(returning_obj)