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__}'
相关推荐
PHP实战开发录3 分钟前
PHP脚本手动能跑定时任务却失败
开发语言·php·开发
郝学胜-神的一滴1 小时前
Effective Python 条款 10 :海象运算符_=
开发语言·python·程序人生·开源
wuyk5551 小时前
Python零基础入门第十四章:异常处理(try-except)
开发语言·python
2601_962078191 小时前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
wuyk5551 小时前
【Socket 进阶之路】第 3 章 TCP 三次握手 & 四次挥手深度剖析|连接建立、断开、状态机、TIME_WAIT 核心工程问题
服务器·开发语言·网络·物联网·网络协议·tcp/ip
卷无止境5 小时前
智能体开发环境ADE浅析,编程工具的下一次范式跃迁
后端·python
彧azz7 小时前
图的存储结构详解:邻接矩阵的原理、实现与应用
开发语言·数据结构·学习·php
平头哥AI7 小时前
Day 22 _ 包装错误别丢链_%w、errors.Is 与 errors.As
android·服务器·学习·golang·go
嵌入式学习菌7 小时前
Modbus‑RTU 数据类型分析
开发语言·单片机·bug
码事漫谈7 小时前
DeepSeek 这波操作很凶
后端