在 url 中混淆密码

Obfuscate password in url

我想在 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,这似乎有些过分了。

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

urlparse returns 命名元组 的(子类)。使用 namedtuple._replace() method 生成新副本,然后使用 geturl() 生成 'unparse'.

密码是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'