Flask中POST请求传递换行符后print无法解析换行的问题
解决Flask接收POST换行符不生效的问题
问题原因
核心问题在于:
- 使用
curl发送请求时,双引号包裹的\n会被当作字面量字符串(即\和n两个独立字符)传递给Flask,而非实际的换行符。 - 但你代码里的
print('\nprinted')是Python的字符串字面量,会被Python解释器自动解析为换行符,因此能正常输出换行效果。
解决方案
方案1:让curl发送实际的换行符
在bash/zsh等支持ANSI-C转义的Shell中,用$'...'包裹请求数据,curl会自动将\n解析为实际换行符:
curl http://127.0.0.1:9090/test -XPOST -d $'test=\nhello'
也可以用printf生成带换行的字符串:
curl http://127.0.0.1:9090/test -XPOST -d "test=$(printf '\nhello')"
此时Flask接收到的test参数自带实际换行符,直接print(test)就能输出预期效果:
hello printed
方案2:后端解析转义字符串
如果前端场景限制必须传递转义后的\n,可以在Flask后端对接收的字符串进行转义解析:
import codecs from flask import Flask, request app = Flask(__name__) @app.route('/test', methods=['GET', 'POST']) def test(): if request.method == 'POST': test = request.form['test'] # 将字面量的\n解析为实际换行符 decoded_test = codecs.decode(test, 'unicode_escape') print(decoded_test) print('\nprinted') return 'Success' if __name__ == '__main__': app.run(port=9090)
这时即使使用原来的curl命令:
curl http://127.0.0.1:9090/test -XPOST -d "test=\nhello"
控制台也会输出:
hello printed
内容的提问来源于stack exchange,提问作者k ho
相关产品推荐
相关产品推荐

