【问题标题】:Python Input SanitizationPython 输入清理
【发布时间】:2015-11-10 08:32:32
【问题描述】:

我需要做一些非常快速的-n-dirty 输入清理,我想基本上将所有<, > 转换为<, >

我想获得与'<script></script>'.replace('<', '<').replace('>', '>') 相同的结果,而不必多次迭代字符串。我知道maketransstr.translate(即http://www.tutorialspoint.com/python/string_translate.htm),但这只会从1 个字符转换为另一个字符。换句话说,一个人不能做这样的事情:

inList = '<>'
outList = ['&lt;', '&gt;']
transform = maketrans(inList, outList)

是否有一个builtin 函数可以在一次迭代中完成这种转换?

我想使用builtin 功能而不是外部模块。我已经知道Bleach

【问题讨论】:

标签: python forms validation input sanitization


【解决方案1】:

你可以使用cgi.escape()

import cgi
inlist = '<>'
transform = cgi.escape(inlist)
print transform

输出:

&lt;&gt;

https://docs.python.org/2/library/cgi.html#cgi.escape

cgi.escape(s[, quote]) 转换中的字符'&'、'' string s 到 HTML 安全的序列。如果您需要显示文本,请使用它 可能在 HTML 中包含此类字符。如果可选标志引用 为真,引号字符 (") 也被翻译;这 有助于包含在由 double 分隔的 HTML 属性值中 引号,如 .请注意,单引号永远不会 已翻译。

【讨论】:

【解决方案2】:

使用 html.escape() - cgi.escape() 在 Python 3 中已弃用

import html
input = '<>&'
output = html.escape(input)
print(output)

&lt;&gt;&amp;

【讨论】:

    【解决方案3】:

    您可以定义自己的函数,循环遍历字符串一次并替换您定义的任何字符。

    def sanitize(input_string):
        output_string = ''
        for i in input_string:
            if i == '>':
                outchar = '&gt;'
            elif i == '<':
                outchar = '&lt;'
            else:
                outchar = i
            output_string += outchar
        return output_string
    

    然后调用

    sanitize('<3 because I am > all of you')
    

    产量

    '&lt;3 because I am &gt; all of you'
    

    【讨论】:

    • 看看 string.join 和列表推导!
    • 对字符串使用 + 是二次的,因为它每次都构造一个新字符串。我认为 CPython 可以将其优化为线性运算,但 PyPy 等其他实现可能无法做到。
    • 重要提示:滚动您自己的消毒剂时,请始终使用明确的列表。如果任何字符不在您允许的集合中 a) 引发错误或 b) 删除它或 c) 替换为某种中性字符...即:else if i in set(string.ascii_letters + string.ascii_digits): ...
    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 2018-02-18
    • 2012-10-15
    • 2011-07-27
    • 2018-02-22
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    相关资源
    最近更新 更多