在网址中模糊密码

时间:2016-12-08 10:16:41

标签: python logging obfuscation urlparse

我想隐藏URL中的密码以进行日志记录。我希望使用urlparse,通过解析,用虚拟密码替换密码,并解析,但这给了我:

>>> from urllib.parse import urlparse
>>> parts = urlparse('https://user:pass@66.66.66.66/aaa/bbb')
>>> parts.password = 'xxx'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

所以替代似乎是this,这似乎有点过分。

使用标准库有没有更简单的方法来替换密码?

1 个答案:

答案 0 :(得分:4)

urlparse返回名为tuple 的的子类。使用namedtuple._replace() method生成新副本,并使用geturl()来“解压缩”。

密码是netloc属性的一部分,可以进一步解析:

from urllib.parse import urlparse

def replace_password(url):
    parts = urlparse(url)
    if parts.password is not None:
        # split out the host portion manually. We could use
        # parts.hostname and parts.port, but then you'd have to check
        # if either part is None. The hostname would also be lowercased.
        host_info = parts.netloc.rpartition('@')[-1]
        parts = parts._replace(netloc='{}:xxx@{}'.format(
            parts.username, host_info))
        url = parts.geturl()
    return url

演示:

>>> replace_password('https://user:pass@66.66.66.66/aaa/bbb')
'https://user:xxx@66.66.66.66/aaa/bbb'