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

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

相关推荐
平凡运维之路2 分钟前
Linux入侵挖矿处理记录
后端
王中阳Go3 分钟前
15 Go Eino AI应用开发实战 | 性能优化
后端·面试·go
shoubepatien21 分钟前
JAVA -- 07
java·后端·intellij-idea
王中阳Go21 分钟前
09 Go Eino AI应用开发实战 | Hertz Web 框架搭建
人工智能·后端·go
Ven%43 分钟前
【AI大模型算法工程师面试题解析与技术思考】
人工智能·python·算法
天勤量化大唯粉44 分钟前
枢轴点反转策略在铜期货中的量化应用指南(附天勤量化代码)
ide·python·算法·机器学习·github·开源软件·程序员创富
無量1 小时前
ConcurrentHashMap实现原理
java·后端
vipbic1 小时前
Strapi 5 怎么用才够爽?这款插件带你实现“建站自由”
后端·node.js
Swizard1 小时前
拒绝“狗熊掰棒子”!用 EWC (Elastic Weight Consolidation) 彻底终结 AI 的灾难性遗忘
python·算法·ai·训练
Spider赵毅1 小时前
python实战 | 如何使用海外代理IP抓取Amazon黑五数据
python·tcp/ip·php