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')

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

相关推荐
程序员爱钓鱼29 分钟前
Go语言实战案例-创建模型并自动迁移
后端·google·go
javachen__35 分钟前
SpringBoot整合P6Spy实现全链路SQL监控
spring boot·后端·sql
uzong6 小时前
技术故障复盘模版
后端
GetcharZp7 小时前
基于 Dify + 通义千问的多模态大模型 搭建发票识别 Agent
后端·llm·agent
桦说编程7 小时前
Java 中如何创建不可变类型
java·后端·函数式编程
IT毕设实战小研7 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi7 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
mit6.8248 小时前
[1Prompt1Story] 滑动窗口机制 | 图像生成管线 | VAE变分自编码器 | UNet去噪神经网络
人工智能·python
没有bug.的程序员8 小时前
JVM 总览与运行原理:深入Java虚拟机的核心引擎
java·jvm·python·虚拟机
甄超锋8 小时前
Java ArrayList的介绍及用法
java·windows·spring boot·python·spring·spring cloud·tomcat