1

我正在尝试使用 SQLite 为 Python 中针对 WolframAlpha 的 API 的某些查询创建一个简单的缓存。问题是某些查询的 SQLite INSERT 失败,我真的不知道为什么。

http://products.wolframalpha.com/api/explorer.html可以准确地运行我运行的两个查询。他们是:

nutritional information of coke

nutritional information of milk

第一个查询的 INSERT 效果很好,但第二个查询失败。

这是负责缓存功能的代码:

def run_query(input_query):
    input_query = query_stub + input_query
    cursor.execute('SELECT response FROM cache WHERE query=?', (input_query,))
    response = cursor.fetchone()

    if response:
        print " Cache hit on: %s" % (input_query)
        response = response[0]
    else:
        print " Cache miss on: %s" % (input_query)
        query = waeo.CreateQuery(input_query)
        print '1'
        response = waeo.PerformQuery(query)
        print '2'
        cursor.execute('INSERT INTO cache VALUES (?, ?)', (input_query, response,))
        print '3'
        conn.commit()
        print '4'

    output_json = xmltodict.parse(response)
    return jsonify(output_json)

该表定义为:

cursor.execute('CREATE TABLE cache (query text, response text)')

以下是部分日志,如您所见,INSERT 失败:

    * Running on http://0.0.0.0:8080/
    Cache miss on: nutritional information of coke
1
2
3
4
127.0.0.1 - - [20/Sep/2013 17:51:16] "GET /wa?item=coke HTTP/1.1" 200 -
    Cache miss on: nutritional information of milk
1
2
127.0.0.1 - - [20/Sep/2013 17:51:47] "GET /wa?item=milk HTTP/1.1" 500 -
4

1 回答 1

0

我按照dwxw的建议做了,发现有编码错误。似乎其中一个查询的结果包含非 ASCII 字符。

除非您使用可以解释 8 位字节串的 text_factory,否则不得使用 8 位字节串

我四处搜索,发现这很容易解决,只需添加以下行(conn 是我的 SQLite 连接):

conn.text_factory = str

感谢您的提示,dwxw。我不知道我自己怎么没有想到...

于 2013-09-21T06:17:58.667 回答