使用Google Cloud SQL时出现KeyError

2 投票
1 回答
821 浏览
提问于 2025-04-17 12:06

我搞不清楚我的代码哪里出错了。
我是不是用错了 executemany 这个方法?

代码如下:

class SQLTester(DirectHandler):
    def get_handler(self):
        from google.appengine.api import rdbms

        command = u"""INSERT IGNORE INTO `ClickLog` 
        (`action` ,`trace_code` ,`url` ,`secret` ,`facebook_id` ,`ip` ,`time` ,`tag` ,`from_url` ,`to_url`)
        values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"""

        conn = rdbms.connect(instance="tagtoosql:tagtoo", database='mysql')
        cursor = conn.cursor()

        #logs = mydb.iter(ClickLog.all(), 500)
        logs = ClickLog.all().fetch(100)
        values = []
        for k in logs:             
            values.append((k.action,
                           k.trace_code,
                           k.url,
                           k.secret,
                           k.facebook_id,
                           k.ip,
                           mydb.to_timestamp1000(k.time),
                           k.tag,
                           k.from_url,
                           k.to_url))

            if len(values) == 100:        
                cursor.executemany(command, values)
                values = []

        cursor.executemany(command, values)

错误信息:

Debug Stack: ExceptionType: <type 'exceptions.KeyError'>
ExceptionValue: [KeyError(<class 'google.appengine.api.datastore_types.Text'>,)]
Traceback (most recent call last):
  File "/base/data/home/apps/s~tagtoo-now-news/worker.356508952957634250/libs/handlers.py", line 331, in get
    self.get_handler(*args, **atts)
  File "/base/data/home/apps/s~tagtoo-now-news/worker.356508952957634250/dashboard/backend.py", line 509, in get_handler
    cursor.executemany(command, values)
  File "/base/python_runtime/python_lib/versions/1/google/storage/speckle/python/api/rdbms.py", line 352, in executemany
    self.execute(statement, args)
  File "/base/python_runtime/python_lib/versions/1/google/storage/speckle/python/api/rdbms.py", line 293, in execute
    bv.type, bv.value = self._EncodeVariable(arg)
  File "/base/python_runtime/python_lib/versions/1/google/storage/speckle/python/api/rdbms.py", line 242, in _EncodeVariable
    value = self._conn.encoders[type(arg)](arg, self._conn.encoders)
KeyError: <class 'google.appengine.api.datastore_types.Text'>

1 个回答

2

来自谷歌的源代码

  def _EncodeVariable(self, arg):
    """Converts a variable to a type and value.

    Args:
      arg: Any tuple, string, numeric, or datetime object.

    Returns:
      A (int, str) tuple, representing a JDBC type and encoded value.

    Raises:
      TypeError: The argument is not a recognized type.
    """
    arg_jdbc_type = self._GetJdbcTypeForArg(arg)
    value = self._conn.encoders[type(arg)](arg, self._conn.encoders)

你的 KeyError 错误是在

self._conn.encoders[type(arg)]

这里出现的,这意味着你的某个参数的类型没有对应的编码器。如果你的参数中有任何不是 元组、字符串、数字或日期时间对象 的类型,那就可能是问题所在。如果你不确定哪个参数出了问题,可以在调用之前打印或记录每个参数的类型,这样就能找到出错的那个。

撰写回答