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__}'
相关推荐
创世宇图10 小时前
【Python工程化实战】Kubernetes 中 Python 应用的优雅启停与健康检查:零停机滚动更新实战
python·云原生·kubernetes·优雅停机
fliter10 小时前
Futures Nostalgia:从 hyper 老派写法看懂 async Rust、Tower 与 Backpressure
后端
zhiSiBuYu051710 小时前
重排序(Rerank)提升检索准确率实战指南
开发语言·python·算法
MageGojo10 小时前
集成企业工商信息查询API:从在线调试到生产级调用实战
python·调试·rest api·api集成·企业信息查询
huangjiazhi_11 小时前
Python3.14编写文件服务器
python
郭梧悠11 小时前
算法:有效的括号
python·算法·leetcode
佛珠散了一地11 小时前
ONNX Runtime GPU 推理配置指南
python
normanhere11 小时前
浪潮云国产化超融合规划和部署案例
服务器·网络
c++之路11 小时前
C++跨平台(九):跨平台字节序统一处理
开发语言·arm开发·c++