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

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

相关推荐
IT_陈寒10 分钟前
7个鲜为人知的JavaScript性能优化技巧,让你的网页加载速度提升50%
前端·人工智能·后端
几颗流星10 分钟前
Rust 常用语法速记 - 迭代器
后端·rust
Ashlee_code11 分钟前
经纪柜台系统解析:从今日国际金融动荡看证券交易核心引擎的变革
python·架构·系统架构·区块链·vim·柜台·香港券商
清空mega26 分钟前
从零开始搭建 flask 博客实验(4)
后端·python·flask
bcbnb29 分钟前
iPhone HTTPS 抓包,从无法抓包到定位问题的流程(Charles/tcpdump/Wireshark/Sniffmaster)
后端
Data_Adventure1 小时前
TypeScript 开发者转向 Java:学习重点与思维迁移指南
后端
吴祖贤1 小时前
Spring AI 零基础入门:从踩坑到上手的完整指南
后端
code_std1 小时前
SpringBoot 登录验证码
java·spring boot·后端
Mos_x1 小时前
@RestController注解
java·后端