在HTML文件中处理Python错误消息中的换行符如"\n"和"\r\n
我想把一个格式错误(或者其他类型的错误)显示给用户。所以我编写了一个flask网络服务器,能够把错误信息以html文件的形式返回给用户。
这个错误信息的输出包含了多个换行符。我想在html中把这些换行符展示给用户。
举个例子,错误信息是这样的:
FormatViolationError - description=Payload for Action is syntactically incorrect or structure for Action, details={'cause': "Payload '{'status': 'Accept'}' for action 'GetCertificateStatus' is not valid: 'Accept' is not one of ['Accepted', 'Failed']\n\nFailed validating 'enum' in schema['properties']['status']:\n {'additionalProperties': False,\n 'description': 'This indicates whether the charging station was able '\n 'to retrieve the OCSP certificate status.\\r\\n',\n
这个错误信息里包含了很多换行符,比如'\n'
或者'\r\n'
。我的想法是把它们替换成'<br>'
。
我有以下代码:
def foo():
try:
somefunction(bar)
except Exception as e:
str_e = repr(e)
# replace the "python" linebreak with html line breaks
str_e_with_linebreaks = str_e.replace("\\r", "<br>")
str_e_with_linebreaks = str_e_with_linebreaks.replace("\\n", "<br>")
return str_e_with_linebreaks
return "No errors were found in the provided data"
返回给用户的html里包含了"<br>"
,但是没有达到我想要的换行效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>String Processor Result</title>
</head>
<body>
<h1>Result</h1>
<p><FormatViolationError - description=Payload for Action is syntactically incorrect or structure for Action, details={'cause': "Payload '{'status': 'Accept', 'Accept' is not one of ['Accepted', 'Failed']<br><br>Failed validating 'enum' in schema['properties']['status']:<br> {'additionalProperties': False,<br> 'description': 'This indicates whether the charging station was able '<br> 'to retrieve the OCSP certificate status.\<br>\<br>',<br> 'enum': ['Accepted', 'Failed'],<br> 'javaType': 'GetCertificateStatusEnum',<br> 'type': 'string'}<br><br>On instance['status']:<br> 'Accept'", 'ocpp_message': <CallResult - unique_id=8c5f1ba7-0167-4ef3-95cd-6efd88a6720f, action=GetCertificateStatus, payload={'status': 'Accept'}>}></p>
<a href="/">Back to input form</a>
</body>
</html>
我卡住了。很可能替换字符的方法行不通。我该如何优雅地格式化这个错误信息,并把它放到html里呢?
在实际的app.py(flask网络服务器)里,我用以下方式把返回的错误信息放进html中:
result = foo(data)
return render_template('result.html', result=result)
1 个回答
你在使用repr这个功能,它会生成一个可以打印的对象表示字符串。
当你在字符串里使用<br>
时,它会被转换成<br>
。这些<
和>
其实是代表ascii里的<和>字符,这样它们就可以在html字符串中使用,而不会被当成标签。就像我们在python中用\
来表示\n
一样。
一个解决办法是,先用repr把对象转换成可打印的字符串,然后再用String.replace("<br>", "<br>")
把<br>
替换成<br>
。
看起来这意味着你不能直接使用repr(e)
,因为那样会搞乱代码。