SAE用flask+MySQL中文'utf8' codec can't decode byte 0xb7解决方法
在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/site-packages/flask/helpers.py”, line 114, in jsonify indent=None if request.is_xhr else 2), mimetype=’application/json’) File “/usr/local/sae/python/lib/python2.7/json/init.py”, line 250, in dumps sort_keys=sort_keys, **kw).encode(obj) File “/usr/local/sae/python/lib/python2.7/json/encoder.py”, line 209, in encode chunks = list(chunks) 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,我编码知识比较薄弱,但大概能猜测到是中文的问题。
遂先检查MySQL的database、table以字段的编码设置,确保
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_request
def 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
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。