在Sina App Engine(SAE)上用python flask框架+MySQL搭app服务器时,select返回中文时jsonify函数报如下错误:(为调试放拜我异常时return的traceback.format_exc())
Traceback (most recent call last): File “/data1/www/htdocs/245/jcguo/1/myapp.py”, line 88, in searchHotel return jsonify(results = data)
……
File “/usr/local/sae/python/lib/python2.7/json/encoder.py”, line 434, in _iterencode for chunk in _iterencode_dict(o, _current_indent_level): File “/usr/local/sae/python/lib/python2.7/json/encoder.py”, line 408, in _iterencode_dict for chunk in chunks: File “/usr/local/sae/python/lib/python2.7/json/encoder.py”, line 332, in _iterencode_list for chunk in chunks: File “/usr/local/sae/python/lib/python2.7/json/encoder.py”, line 390, in _iterencode_dict yield _encoder(value) UnicodeDecodeError: ‘utf8’ codec can’t decode byte 0xb7 in position 4: invalid start byte
大概意思是jsonify时utf8解码器不能解码0xb7,我编码知识比较薄弱,但大概能猜测到是中文的问题。
遂先检查SAE上MySQL的database、table以字段的编码设置(应用管理->服务管理->MySQL),确保:
SHOW CREATE DATABASE app_jcguo;
返回:
CREATE DATABASE `app_jcguo` /*!40100 DEFAULT CHARACTER SET utf8 */
以及:
SHOW CREATE TABLE Hotels
添加了default charset:
CREATE TABLE `Hotels` ( `id` int(11) NOT NULL, `name` varchar(40) DEFAULT NULL, `city` varchar(10) DEFAULT NULL, `address` text, `price` int(11) DEFAULT NULL, `total` int(11) DEFAULT NULL, `avail` int(11) DEFAULT NULL, `pic_b` varchar(40) DEFAULT NULL, `pic_s` varchar(40) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8
并且保证要填入中文的字段都是varchar类型并且设置为utf8_general_ci:
设置检查完毕但服务器还是报错,最后只好Google四处寻找解决方案。发现原来是MySQLdb.connect()还要设置一遍charset来指定cursor取数据库数据的格式:
@app.before_requestdef before_request(): g.db = MySQLdb.connect( MYSQL_HOST, MYSQL_USER, MYSQL_PASS, MYSQL_DB, port=int(MYSQL_PORT), charset = 'utf8' )
第一次用MySQL存中文,遇到此坑,遂记录在Blog上。SQLite所有操作默认都是UTF-8,TAT,老用python+SQLite就忽略了这个问题。
对了,文件头中别忘了添加编码注释:
# -*- coding:utf8 -*-#encoding = utf-8