Is there a Python equivalent to the PHP function htmlspecialchars()?

折月煮酒 提交于 2020-01-22 05:48:04

问题


Is there a similar or equivalent function in Python to the PHP function htmlspecialchars()? The closest thing I've found so far is htmlentitydefs.entitydefs().


回答1:


Closest thing I know about is cgi.escape.




回答2:


from django.utils.html import escape
print escape('<div class="q">Q & A</div>')



回答3:


You probably want xml.sax.saxutils.escape:

from xml.sax.saxutils import escape
escape(unsafe, {'"':'&quot;'}) # ENT_COMPAT
escape(unsafe, {'"':'&quot;', '\'':'&#039;'}) # ENT_QUOTES
escape(unsafe) # ENT_NOQUOTES

Have a look at xml.sax.saxutils.quoteattr, it might be more useful for you




回答4:


The html.entities module (htmlentitydefs for python 2.x) contains a dictionary codepoint2name which should do what you need.

>>> import html.entities
>>> html.entities.codepoint2name[ord("&")]
'amp'
>>> html.entities.codepoint2name[ord('"')]
'quot'



回答5:


I think the simplest way is just to use replace:

text.replace("&", "&amp;").replace('"', "&quot;").replace("<", "&lt;").replace(">", "&gt;")

PHP only escapes those four entities with htmlspecialchars. Note that if you have ENT_QUOTES set in PHP, you need to replace quotes with &#039; rather than &quot;.




回答6:


If you are using django 1.0 then your template variables will already be encoded and ready for display. You also use the safe operator {{ var|safe }} if you don't want it globally turned on.




回答7:


Building on @garlon4 answer, you can define your own htmlspecialchars(s):

def htmlspecialchars(text):
    return (
        text.replace("&", "&amp;").
        replace('"', "&quot;").
        replace("<", "&lt;").
        replace(">", "&gt;")
    )


来源:https://stackoverflow.com/questions/931423/is-there-a-python-equivalent-to-the-php-function-htmlspecialchars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!