Securely Storing Credentials in Python with Keyring
When building Python scripts that connect to databases, APIs, or other services, one of the first challenges you’ll face is how to securely handle credentials. Hardcoding passwords in your scripts is a security risk. Environment variables are better but still have limitations. The Python keyring library offers an elegant solution by leveraging your operating system’s native credential store.
The Problem with Hardcoded Credentials
Many developers start by embedding usernames and passwords directly in their scripts. This creates several problems: credentials end up in version control, they’re visible to anyone with file access, and updating them requires modifying code.
Using the Keyring Library
The keyring library provides a cross-platform way to access the system’s credential store — Windows Credential Locker, macOS Keychain, or Linux’s Secret Service. This means your credentials are encrypted at rest and managed by the OS.
Installation
pip install keyring
Storing a Credential
import keyring
keyring.set_password("my_database", "admin_user", "my_secure_password")
Retrieving a Credential
import keyring
password = keyring.get_password("my_database", "admin_user")
print(password) # my_secure_password
Why This Matters for Analytics Teams
For teams building automated data pipelines, ETL processes, or reporting scripts, credential management is critical. The keyring approach ensures that:
- Credentials never appear in source code or configuration files
- Each developer/server can maintain its own credential store
- The operating system handles encryption and access control
- Scripts remain portable across environments
This is a summary of the original article. Full content is being migrated from the previous site.
