我在Windows 7机器上有一个Mercurial密钥环。 我正在使用Python keyring
库从Mercurial密钥环获取用户凭据。
我可以使用以下命令检索给定用户名的密码:
keyring.get_password('Mercurial', 'user@@etc')
是否有类似的函数可以检索用户名?
我在Windows 7机器上有一个Mercurial密钥环。 我正在使用Python keyring
库从Mercurial密钥环获取用户凭据。
我可以使用以下命令检索给定用户名的密码:
keyring.get_password('Mercurial', 'user@@etc')
是否有类似的函数可以检索用户名?
在Windows上,我可以使用以下代码获取用户名和密码(即“凭据”):
c = keyring.get_credential("servicename", None)
请注意,在macOS上这是无法实现的,keyring
后端没有搜索条目的功能——也就是说,您需要知道用户名。尽管如此,我想本地代码可能允许您这样做,请参见官方文档。
keyring.get_credential
代替。
keyring
只被设计用来存储密码,但你可以滥用 get_password
来分别存储用户名。import keyring
# store username & password
keyring.set_password("name_of_app", "username", "user123")
keyring.set_password("name_of_app", "password", "pass123")
# retrieve username & password
username = keyring.get_password("name_of_app", "username")
password = keyring.get_password("name_of_app", "password")
或者,如果您想将用户名与密码配对:
import keyring
service_id = "name_of_app"
username = "user123"
# store username & password
keyring.set_password(service_id, "username", username)
keyring.set_password(service_id, username, "pass123")
# retrieve username & password
username = keyring.get_password(service_id, "username")
password = keyring.get_password(service_id, username)
感谢Dustin Wyatt和Alex Chan提供这个解决方案。
您可以使用 keyring 15.2.0 中添加的 get_credential
函数来检索用户名。
import keyring
keyring.set_password("example_service", "example_username", "example_password")
credentials = keyring.get_credential("example_service", None)
if credentials is not None:
username = credentials.username # example_username
password = credentials.password # example_password
感谢MShekow和Eelco van Villet提供了类似的答案
import getpass
import keyring
import requests
service_name = "Name of the keyring"
credentials = keyring.get_credential(service_name, None)
if credentials is None:
username = input("Username: ")
password = getpass.getpass()
keyring.set_password(service_name,username, password)
else:
username = credentials.username
password = credentials.password
然后你可以进行你的操作,例如使用请求将帖子发布到api。如果失败,请删除密钥环以强制重新请求凭据。
response = requests.post('url_to_api', auth=requests.auth.HTTPBasicAuth(username, password))
try:
response.raise_for_status()
except requests.exceptions.HTTPError as err:
keyring.delete_password(service_name, username)
raise
如果登录成功,下次就不必再输入用户名和密码。
c.username
和c.password
这样的方式访问用户名和密码。 - Felix Zumsteinget_credential
函数从 Keyring 15.2.0 版本开始提供。 - Stevoisiak