liveBook · Manning

Credential store

As explained in Software Engineering for Data Scientists

A credential store is a protected operating-system facility for storing and retrieving authentication secrets.

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

How Software Engineering for Data Scientists covers it

How deep it goes
Defines operating-system storage and demonstrates keyring installation, storage, retrieval, and database use, but only briefly names alternatives.
Examples
Uses keyring entries named database_credentials and a pyodbc SQL Server connection string.
What you can do after
Operate/configure keyring to store and retrieve credentials without hard-coding passwords in Python.
How it connects
Connects credential handling with Python, keyring, database connections, SQL Server, and credential-security libraries.

Also explained in

Compare how 3 books explain credential store →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Engineering for Data Scientists. The section links point to the parts of the book it draws on.