django html中文乱码,如何使用Python/Django执行HTML解码/编码?

对于Django用例,有两个答案。下面是它的django.utils.html.escape函数,供参考:def escape(html):

"""Returns the given HTML with ampersands, quotes and carets encoded."""

return mark_safe(force_unicode(html).replace('&', '&').replace('

t;').replace('>', '>').replace('"', '"').replace("'", '''))

为了扭转这种情况,Jake的答案中描述的Cheetah函数应该可以工作,但是缺少一个引号。此版本包括一个更新的元组,其替换顺序是相反的,以避免出现对称问题:def html_decode(s):

"""

Returns the ASCII decoded version of the given HTML string. This does

NOT remove normal HTML tags like

.

"""

htmlCodes = (

("'", '''),

('"', '"'),

('>', '>'),

('

('&', '&')

)

for code in htmlCodes:

s = s.replace(code[1], code[0])

return s

unescaped = html_decode(my_string)

然而,这不是一个通用的解决方案;它只适用于用django.utils.html.escape编码的字符串。更一般地说,最好还是使用标准库:# Python 2.x:

import HTMLParser

html_parser = HTMLParser.HTMLParser()

unescaped = html_parser.unescape(my_string)

# Python 3.x:

import html.parser

html_parser = html.parser.HTMLParser()

unescaped = html_parser.unescape(my_string)

# >= Python 3.5:

from html import unescape

unescaped = unescape(my_string)

建议:在数据库中存储未转义的HTML可能更有意义。如果可能的话,从美化组得到未美化的结果是值得研究的,并且完全避免这个过程。

对于Django,转义只在模板呈现期间发生;因此为了防止转义,只需告诉模板引擎不要转义字符串。为此,请在模板中使用以下选项之一:{{ context_var|safe }}

{% autoescape off %}

{{ context_var }}

{% endautoescape %}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值