在HTML文件中处理Python错误消息中的换行符如"\n"和"\r\n

0 投票
1 回答
32 浏览
提问于 2025-04-12 05:38

我想把一个格式错误(或者其他类型的错误)显示给用户。所以我编写了一个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>&lt;FormatViolationError - description=Payload for Action is syntactically incorrect or structure for Action, details={&#39;cause&#39;: &#34;Payload &#39;{&#39;status&#39;: &#39;Accept&#39;, &#39;Accept&#39; is not one of [&#39;Accepted&#39;, &#39;Failed&#39;]&lt;br&gt;&lt;br&gt;Failed validating &#39;enum&#39; in schema[&#39;properties&#39;][&#39;status&#39;]:&lt;br&gt;    {&#39;additionalProperties&#39;: False,&lt;br&gt;     &#39;description&#39;: &#39;This indicates whether the charging station was able &#39;&lt;br&gt;                    &#39;to retrieve the OCSP certificate status.\&lt;br&gt;\&lt;br&gt;&#39;,&lt;br&gt;     &#39;enum&#39;: [&#39;Accepted&#39;, &#39;Failed&#39;],&lt;br&gt;     &#39;javaType&#39;: &#39;GetCertificateStatusEnum&#39;,&lt;br&gt;     &#39;type&#39;: &#39;string&#39;}&lt;br&gt;&lt;br&gt;On instance[&#39;status&#39;]:&lt;br&gt;    &#39;Accept&#39;&#34;, &#39;ocpp_message&#39;: &lt;CallResult - unique_id=8c5f1ba7-0167-4ef3-95cd-6efd88a6720f, action=GetCertificateStatus, payload={&#39;status&#39;: &#39;Accept&#39;}&gt;}&gt;</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 个回答

0

你在使用repr这个功能,它会生成一个可以打印的对象表示字符串。

当你在字符串里使用<br>时,它会被转换成&lt;br&gt;。这些&lt;&gt;其实是代表ascii里的<和>字符,这样它们就可以在html字符串中使用,而不会被当成标签。就像我们在python中用\来表示\n一样。

一个解决办法是,先用repr把对象转换成可打印的字符串,然后再用String.replace("&lt;br&gt;", "<br>")&lt;br&gt;替换成<br>

看起来这意味着你不能直接使用repr(e),因为那样会搞乱代码。

撰写回答