我想向用户显示 FormatViolationError (或其他类型的错误)。因此,我编写了一个 Flask Web 服务器,将 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 Web 服务器)中。我将返回的错误包含在 html 中:
result = foo(data)
return render_template('result.html', result=result)
您正在使用 repr 生成给定对象的可打印表示字符串。
当您在字符串中使用
<br>
时,它会转换为 <br>
。这些 <
和 >
代表 ascii < and > 字符,因此它们可以在 html 字符串中使用,而不会被识别为标签。有点像我们在 python 中使用 \n
中的 \ 。
解决方案是首先使用 repr 转换为可打印的表示字符串,然后使用
<br>
替换为 <br>
String.replace("<br>", "<br>")