解决Flask读取mysql数据库的中文乱码问题

    技术2022-07-14  80

    # -*- coding: utf-8 -*- from flask import Flask, render_template import pymysql from sqlalchemy import create_engine app = Flask(__name__) # 解决中文乱码的问题,将json数据内的中文正常显示 app.config['JSON_AS_ASCII'] = False # 开启debug模式 app.config['DEBUG'] = True @app.route('/gender', methods=['GET', 'POST']) def gender(): conn = create_engine("mysql+pymysql://root:123456@localhost/flask") cur = conn.connect() # 数据引擎 result = cur.execute("select * from genderdf") gender = [] data = [] for item in result: gender.append(item[0]) data.append(item[1]) return {'gender': gender, 'data': data} if __name__ == "__main__": app.run(debug=True)

    Flask能运行成功,但中文显示的是乱码

    如图所示 解决方法:

    在相对应的python中加入

    # 解决中文乱码的问题,将json数据内的中文正常显示 app.config['JSON_AS_ASCII'] = False # 开启debug模式 app.config['DEBUG'] = True

    再运行就可以得到中文显示

    Processed: 0.046, SQL: 9