App engine - Python: UnicodeDecodeError: 'utf8' codec can't decode byte 0xe1 in position 1: invalid continuation byte
我正在用python版本2.7做一个小的flask-server-in-app-engine(google-cloud-platform),我有一个带有重音标记的字母和"?"的问题。信。我在这里共享我的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | @app.route('/faq', methods=['GET']) def get_faq(): response = _get_faq() return json.dumps(response), 200, {'Content-Type': 'application/json'} def _get_faq(): db = MySQLdb.connect(host=CLOUDSQL_CONNECTION_HOST, user=CLOUDSQL_USER, passwd=CLOUDSQL_PASSWORD, use_unicode=True, charset='utf8') query ="SELECT question, answer FROM faq_table" cursor = db.cursor(cursorclass=MySQLdb.cursors.DictCursor) cursor.execute(query) result=cursor.fetchall() faq_response = [] for row in result: faq_response.append( { "question": row["question"], "answer": row["answer"] } ) return faq_response |
但当我将此代码上载到应用程序引擎并调用此服务时,服务器将发送代码500,并在错误报告中显示下一条消息:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf3 in position 22: invalid continuation byte
我不能像这样解决这个问题:
1 | json.dumps(response).encode('utf-8') |
我总是有同样的反应。接下来是跟踪:
at iterencode (/base/alloc/tmpfs/dynamic_runtimes/python27g/ec315266546cb44c/python27/python27_dist/lib/python2.7/json/encoder.py:270)
at encode (/base/alloc/tmpfs/dynamic_runtimes/python27g/ec315266546cb44c/python27/python27_dist/lib/python2.7/json/encoder.py:207)
at dumps (/base/alloc/tmpfs/dynamic_runtimes/python27g/ec315266546cb44c/python27/python27_dist/lib/python2.7/json/init.py:244)
at get_faq
(/base/data/home/apps/xxxxx/yyyyyyyy:nnnnnnn.mmmmmmm/main.py:7)
有人能帮忙吗?谢谢
尝试:
1 | json.dumps(response.encode('utf-8')) |