Flask返回浏览器无乱码方法

python 复制代码
# -*- 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')

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

相关推荐
段一凡-华北理工大学16 分钟前
工业智能体:从Codex/Claude到项目实战~系列文章05:从“AI助手“到“工业智能体“:能力跃迁与落地范式
人工智能·python·claude·codex·工业智能体·高炉炼铁智能化
独泪了无痕24 分钟前
探索Pinyin4j-Java中的拼音转换利器
java·后端
码事漫谈39 分钟前
从 Coze 居然要下线了说起
后端
深蓝AI39 分钟前
ContextVar 到线程池就丢了?asyncio.to_thread 和 run_in_executor 实测
python
想不到一个好的ID1 小时前
智能体开发
后端
皮皮林5511 小时前
为什么数据库连接池不采用 IO 多路复用?
后端
岁月宁静2 小时前
什么是 Agent:从"会聊天"到"会做事"
人工智能·python
岁月宁静2 小时前
AI 应用开发工程师简历怎么写:HR 初筛、技术复筛、面试追问,三道关卡各看什么?
人工智能·python·面试
来让爷抱一个2 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
小肝一下4 小时前
3.基础语法(3)
python