Bootstrap

Flask返回浏览器无乱码方法

# -*- coding: utf-8 -*-
from flask import Flask, request, jsonify, Response
import os
import json
import re
from datetime import datetime
import logging
import sys
import crawling_web_knowledge

app = Flask(__name__)


app.json.ensure_ascii = False  # 解决中文乱码问题


@app.route('/')
def index1():
    return {"code": 200, "message": "success"}


@app.route('/message', methods=['GET', 'POST'])
def index2(type="new"):
    start_time = datetime.now()

    if request.method == 'GET':
        content = request.args.get('content')
    elif request.method == 'POST':
        content = request.form.get('content')

    resdict = 方法
    resdict["code"] = 200
    resdict["input"] = content

    end_time = datetime.now()
    # print("计时结束", end)
    # 计算时长
    duration = end_time - start_time
    print(f"任务执行时长: {duration.total_seconds()}")

    resdict = json.dumps(resdict, ensure_ascii=False)
    # 创建一个Response对象,并设置Content-Type为application/json
    response = Response(resdict, content_type='application/json')
    logging.info("#content:{}###resdict:{}#".format(content, response))

    return response


if __name__ == '__main__':
    logging.basicConfig(stream=sys.stdout, format='%(asctime)s %(levelname)s:%(message)s', level=logging.INFO,
                        datefmt='%I:%M:%S')
    app.run(debug=True, port=XXX, host='0.0.0.0')

1、先json.dumps(对应字典, ensure_ascii=False)编码

2、然后

Response(对应字典, content_type='application/json')

方可解决浏览器显示乱码问题

;