Hard-coding passwords in Python can leak secrets or enable unauthorized access. A credential store provides protected operating-system storage that Python can use to save and retrieve authentication credentials. section 9.2.4
Listing 9.11 Use keyring’s set_password method to store a username and password. The first parameter of this method is an arbitrary name that you want to associate with the username/password combination. In this case, we store the username and password as database_credentials.
import keyring #1
keyring.set_password("database_credentials", #2
"secret_username",
"secret_password")
Use keyring.set_password with a service name, username, and password to save credentials in the operating-system credential store. section 9.2.4
Listing 9.12 To retrieve the stored credentials, you can use the get_password method from keyring. For this method, we just need to input the name associated with the credentials we want to retrieve, along with the username.
keyring.get_password("database_credentials", #1
"secret_username")
Retrieve a stored password with the same service name and username, even from a later Python session. section 9.2.4
Supplying database credentials
A database connection can retrieve the password from keyring and place it into a SQL Server connection string for pyodbc, instead of storing the password directly in code. section 9.2.4
Listing 9.13 This code snippet is an example of passing a username and password into a database connection string.
import pyodbc #1
import keyring #1
password = keyring.get_password("database_credentials", #2
"secret_username")
conn_str = ("Driver={SQL Server};"
"Server=servername"
"Database=databasename;"
"UID=secret_username;"
f"PWD={password};")
conn = pyodbc.connect(conn_str) #3
See the focused pyodbc example that retrieves a password from keyring and builds a SQL Server connection. section 9.2.4


