Redact and remove password from URL

做~自己de王妃 提交于 2020-05-29 07:26:08

问题


I have an URL like this:

https://user:password@example.com/path?key=value#hash

The result should be:

https://user:???@example.com/path?key=value#hash

I could use a regex, but instead I would like to parse the URL a high level data structure, then operate on this data structure, then serializing to a string.

Is this possible with Python?


回答1:


You can use the built in urlparse to query out the password from a url. It is available in both Python 2 and 3, but under different locations.

Python 2 import urlparse

Python 3 from urllib.parse import urlparse

Example

from urllib.parse import urlparse

parsed = urlparse("https://user:password@example.com/path?key=value#hash")
parsed.password # 'password'

replaced = parsed._replace(netloc="{}:{}@{}".format(parsed.username, "???", parsed.hostname))
replaced.geturl() # 'https://user:???@example.com/path?key=value#hash'

See also this question: Changing hostname in a url



来源:https://stackoverflow.com/questions/46905367/redact-and-remove-password-from-url

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