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

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

相关推荐
ywf121525 分钟前
前端的dist包放到后端springboot项目下一起打包
前端·spring boot·后端
程序员爱钓鱼25 分钟前
Go排序核心库: sort包深度指南
后端·面试·go
2501_9454235430 分钟前
用Matplotlib绘制专业图表:从基础到高级
jvm·数据库·python
2301_7938046931 分钟前
使用Python处理计算机图形学(PIL/Pillow)
jvm·数据库·python
吴佳浩7 小时前
GPU 编号进阶:CUDA\_VISIBLE\_DEVICES、多进程与容器化陷阱
人工智能·pytorch·python
大阿明7 小时前
Spring Boot(快速上手)
java·spring boot·后端
全栈凯哥7 小时前
18.Python中的导入类完全指南
python
sunwenjian8868 小时前
Java进阶——IO 流
java·开发语言·python
墨香幽梦客8 小时前
API集成技术规范:RESTful与GraphQL在企业系统对接中的应用对比
后端·restful·graphql
guts3508 小时前
图像篡改数据集下载:COVERAGE、CASIA
python·数据集