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'>
问题原因
-
当在 Flask 中返回字符串时,浏览器将其作为 HTML 解析
-
<class 'str'>中的字符<与>在 HTML 中有特殊含义,即标签的界定符
处理策略
- 使用 HTML 实体编码
python
@app.route('/user/<string:username>')
def show_string(username):
type_str = str(type(username))
type_str_escaped = type_str.replace('<', '<').replace('>', '>')
return f'type: string, value: {username}, python_type: {type_str_escaped}'
- 使用 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)}'
- 使用 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)}'
- 设置 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')
- 避免使用 HTML 特殊字符
python
@app.route('/user/<string:username>')
def show_string(username):
return f'type: string, value: {username}, python_type: {type(username).__name__}'