Python Flask 开发:在 Flask 中返回字符串时,浏览器将其作为 HTML 解析

python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    return f'type: string, value: {username}, python_type: {str(type(username))}'
  • 在 Python Flask 开发中,访问上述接口 /user/john_doe 时,在浏览器中,会输出以下结果

    type: string, value: john_doe, python_type:

  • 但是,在控制台中,会输出以下结果

    type: string, value: john_doe, python_type: <class 'str'>

问题原因
  1. 当在 Flask 中返回字符串时,浏览器将其作为 HTML 解析

  2. <class 'str'> 中的字符 <> 在 HTML 中有特殊含义,即标签的界定符

处理策略
  1. 使用 HTML 实体编码
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    type_str = str(type(username))
    type_str_escaped = type_str.replace('<', '&lt;').replace('>', '&gt;')
    return f'type: string, value: {username}, python_type: {type_str_escaped}'
  1. 使用 escape 函数
python 复制代码
from markupsafe import escape
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    type_str = str(type(username))
    return f'type: string, value: {username}, python_type: {escape(type_str)}'
  1. 使用 Markup 类
python 复制代码
from markupsafe import Markup
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    type_str = str(type(username))
    return f'type: string, value: {username}, python_type: {Markup.escape(type_str)}'
  1. 设置 content-type 为纯文本
python 复制代码
from flask import Flask, Response
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    content = f'type: string, value: {username}, python_type: {str(type(username))}'
    return Response(content, content_type='text/plain')
  1. 避免使用 HTML 特殊字符
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    return f'type: string, value: {username}, python_type: {type(username).__name__}'
相关推荐
共享家95272 小时前
搭建 AI 聊天机器人:”我的人生我做主“
前端·javascript·css·python·pycharm·html·状态模式
疯狂的喵3 小时前
C++编译期多态实现
开发语言·c++·算法
2301_765703143 小时前
C++中的协程编程
开发语言·c++·算法
m0_748708053 小时前
实时数据压缩库
开发语言·c++·算法
Hgfdsaqwr3 小时前
Python在2024年的主要趋势与发展方向
jvm·数据库·python
lly2024063 小时前
jQuery Mobile 表格
开发语言
一晌小贪欢4 小时前
Python 测试利器:使用 pytest 高效编写和管理单元测试
python·单元测试·pytest·python3·python测试
小文数模4 小时前
2026年美赛数学建模C题完整参考论文(含模型和代码)
python·数学建模·matlab
惊讶的猫4 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
Halo_tjn4 小时前
基于封装的专项 知识点
java·前端·python·算法