Python中的SQLite插入失败

时间:2013-09-20 09:06:32

标签: python sqlite caching wolframalpha

我正在尝试使用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 -

1 个答案:

答案 0 :(得分:0)

我按照dwxw的建议做了,发现存在编码错误。看起来其中一个查询的结果包含非ASCII字符。

  

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

我四处搜索,发现只需添加以下行就可以轻松解决这个问题(conn是我的SQLite连接):

  

conn.text_factory = str

感谢小费,dwxw。我不知道自己怎么也没想到......