【问题标题】:django python encode produce strange outputdjango python encode 产生奇怪的输出
【发布时间】:2020-11-18 05:19:36
【问题描述】:

我用 html 代码生成一个字符串。我将这些字符串插入到这样的模板中:

header = render_to_string('header.html', {'content': header_content})

模板如下所示:

  ...
  {% autoescape off %}
  {{ content }}
  {% endautoescape %}
  </body>
  ...

现在我有一个名为“header”的字符串变量。 我想将这些字符串作为 html 文件存储在我的存储 (AWS S3) 中。

我尝试使用 django contentfile 创建一个临时文件。为此,我必须对字符串进行编码。它看起来像这样:

self.export_settings.header.save("header.html", ContentFile(header.encode()))

现在我的 s3 存储中有一个 html 文件,但有时内容很奇怪。 例如,我有一个空列的表。

在我调用header.encode() 之前,它看起来像这样(这是我在模板中插入的内容的一部分,它来自使用 TinyMCE 创建它的用户):

<tbody>
<tr>
<td style="width: 32.1574%;">Test</td>
<td style="width: 32.237%;"> </td>
<td style="width: 32.237%; text-align: right;">Site <span class="page"> of <span class="topage"></td>
</tr>
</tbody>
</table>
</body>

但是在我调用.encode() 并将其保存到存储中后,html 文件在第二列中显示了这一点:

为什么?那不是我想要的。我想将代表 html 代码的字符串存储为 html 文件,而不将内容转换为奇怪的字符。 我已经读过 utf-8 编码可能是造成这种情况的原因,但是如果没有编码,我怎么能做我想做的事情呢? ContentFile 需要字节,而不是字符串。

【问题讨论】:

  • 如果您认为需要 UTF-8,为什么不将 'utf-8' 作为参数传递给 encode
  • 我不知道 utf-8 是否最适合我。但我相信 utf-8 是编码的默认值。
  • 你是对的,str.encode 的默认值是utf-8。但并非总是如此,我不知道什么时候改变了。
  • 我尝试使用header.encode('utf-8'),但输出相同。
  • 我必须假设您的模板有一个隐藏字符,该字符未出现在您的问题中。这使得这个问题有点难以回答。

标签: python django utf-8 encode


【解决方案1】:

我已经通过将编码设置为 ascii 来解决这个问题,因为我已经阅读了使用 ascii 编码的 ContentFile。代码如下:

ContentFile(header.encode('ascii', 'xmlcharrefreplace'))

现在一切正常!

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 2015-08-18
    • 2016-03-15
    • 1970-01-01
    • 2012-12-04
    • 2012-07-19
    相关资源
    最近更新 更多