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__}'
相关推荐
csbysj20202 小时前
Scala 类和对象
开发语言
拾忆,想起2 小时前
设计模式:软件开发的可复用武功秘籍
开发语言·python·算法·微服务·设计模式·性能优化·服务发现
狮子座的男孩2 小时前
html+css基础:07、css2的复合选择器_伪类选择器(概念、动态伪类、结构伪类(核心)、否定伪类、UI伪类、目标伪类、语言伪类)及伪元素选择器
前端·css·经验分享·html·伪类选择器·伪元素选择器·结构伪类
沐知全栈开发2 小时前
HTTP/HTTPS 简介
开发语言
听风吟丶2 小时前
Spring Boot 自动配置深度解析:原理、实战与源码追踪
前端·bootstrap·html
跟着珅聪学java2 小时前
HTML中设置<select>下拉框默认值的详细教程
开发语言·前端·javascript
IT_陈寒2 小时前
JavaScript 性能优化:5个被低估的V8引擎技巧让你的代码提速50%
前端·人工智能·后端
slongzhang_2 小时前
PHP图片处理|画布入门
开发语言·php
沃斯堡&蓝鸟2 小时前
DAY28 元组和OS模块
python·元组与os模块