【问题标题】:strip username and password from url with basic auth使用基本身份验证从 url 中删除用户名和密码
【发布时间】:2021-12-08 11:07:30
【问题描述】:

我正在尝试从 url 中获取用户名和密码并将其重新组合在一起,以便以完整的形式再次使用它,但没有基本的身份验证部分。

我正在尝试类似下面的方法,但结果不是我所期望的。

from urllib.parse import urlsplit, urlunsplit
parts = urlsplit("http://user:pwd@host:8080/path?query=foo", allow_fragments=True)
auth = (parts.username, parts.password)
print(urlunsplit((parts.scheme, parts.hostname, str(parts.port), parts.path, parts.query)))
# http://host/8080?/path#query=foo

如果我可以在部件上将用户名和密码设置为 None 并调用 geturl 但我收到无法更改属性的错误,那就更好了。

from urllib.parse import urlsplit
parts = urlsplit("http://user:pwd@host:8080/path?query=foo", allow_fragments=True)
auth = (parts.username, parts.password)
parts.password = None
parts.username = None
print(parts.geturl())
# AttributeError: can't set attribute

注意,我想将用户名和密码保存在单独的元组中。

【问题讨论】:

  • 根据文档urlsplit 返回一个namedtuple。您可以在元组中通过说part._replace(password=None, username=None)replace fields,这将返回一个新的namedtuple(因为part 是不可变的)。
  • 您是否考虑过使用re。示例:tuple(re.search("\/.*?\@", my_url).group(0)[2:-1].split(":"))
  • 我已经试过了,它已经说了未知的论点。我想了一分钟把它包括在内,但由于它是一个 private 方法,我认为无论如何我们都不应该实际使用它。 ValueError: Got unexpected field names: ['password', 'username']

标签: python


【解决方案1】:

urlunsplit 需要一个看起来与urlsplit 返回的相同的元组。该元组中的第二个元素是 netloc - 看起来像: user:pwd@host:port

所以你需要传递类似的东西。您可以通过修改从urlsplit 获得的parts.netloc 并将其传递给urlunsplit 来做到这一点:

from urllib.parse import urlsplit, urlunsplit

parts = urlsplit("http://user:pwd@host:8080/path?query=foo", allow_fragments=True)
auth = (parts.username, parts.password)

netloc = parts.netloc.split('@')[1]  # ignore the auth part. You should check the length after the split obviously
reconstruction_parts = (parts.scheme, netloc, parts.path, parts.query, parts.fragment)

print(urlunsplit(reconstruction_parts))

结果:

http://host:8080/path?query=foo

【讨论】:

    猜你喜欢
    • 2014-05-10
    • 1970-01-01
    • 2016-04-07
    • 2017-10-03
    • 2020-04-18
    • 2017-06-26
    • 1970-01-01
    • 2016-04-19
    • 2017-04-17
    相关资源
    最近更新 更多