How To Securely Save Credentials in Python
Like API tokens, passwords, or other sensitive data #PurePythonSeries — Episode #19
The command EDITOR="code --wait" rails credentials:edit is used in Ruby on Rails to open the credentials file in the Visual Studio Code editor, and the --wait flag makes the command wait until the editor is closed before proceeding. Here is my first attempt, followed by a script run by Chris Oliver explaining everything in detail.

In Python, there isn’t a direct equivalent for editing files with an external editor like this, but you can achieve similar functionality by using the subprocess module to open a file with VS Code or any other text editor.
Here’s how you can do it in Python:
import subprocess
# Specify the file you want to edit
file_to_edit = 'path/to/your/file.txt'
# Open the file in Visual Studio Code and wait for the editor to close
subprocess.run(["code", "--wait", file_to_edit])This Python script opens the specified file in VS Code and waits for the editor to close before continuing with the rest of the script, similar to the Rails command.
Let’s get started!
To securely save credentials like API tokens, passwords, or other sensitive data in Python, you should avoid hard-coding these values directly into your scripts. Instead, consider using environment variables, encrypted storage, or a configuration management system. Here are a few secure methods to handle credentials in Python:
1. Environment Variables:
Environment variables are a common way to store sensitive data securely. This approach keeps credentials out of your codebase and allows you to access them dynamically.
Setting Environment Variables
You can set environment variables in your operating system or through a shell before running your Python script:
For Unix-like systems (Linux, macOS):
export API_TOKEN='your_secure_token_here'For Windows:
set API_TOKEN=your_secure_token_hereAccessing Environment Variables in Python
Use the os module to access these variables in your Python script:
import os
api_token = os.getenv('API_TOKEN')
if not api_token:
raise ValueError("No API token found. Set the API_TOKEN environment variable.")
print(f'Using API token: {api_token}')2. Using .env Files:
A .env file can store environment variables locally. This file should be kept secure and not included in version control.
- Create a
.envfile:
API_TOKEN=your_secure_token_hereUse the python-dotenv library to load environment variables from the .env file:
First, install python-dotenv:
pip install python-dotenv
Then, use it in your script:
from dotenv import load_dotenv
import os
load_dotenv() # Load environment variables from .env file
api_token = os.getenv('API_TOKEN')
if not api_token:
raise ValueError("No API token found. Check your .env file.")
print(f'Using API token: {api_token}')3. Secure Storage with Keyring:
For storing credentials securely on your system, use the keyring library, which integrates with your operating system’s credential store (like macOS Keychain, Windows Credential Locker, or Linux Secret Service).
- Install the
keyringlibrary:
pip install keyring
Store and retrieve credentials:
import keyring
# Store the API token securely
keyring.set_password('system_name', 'username', 'your_secure_token_here')
# Retrieve the stored API token
api_token = keyring.get_password('system_name', 'username')
if not api_token:
raise ValueError("No API token found in the keyring.")
print(f'Using API token: {api_token}')Replace 'system_name' and 'username' with appropriate identifiers for your application.
4. Using Encrypted Files:
You can also store sensitive data in encrypted files using libraries like cryptography. This method requires a decryption step each time you need access to the data.
- Install
cryptography:
pip install cryptography
Encrypt and decrypt data:
from cryptography.fernet import Fernet
# Generate and save a key (do this once and keep the key secure)
key = Fernet.generate_key()
with open('secret.key', 'wb') as key_file:
key_file.write(key)
# Load the key
with open('secret.key', 'rb') as key_file:
key = key_file.read()
cipher_suite = Fernet(key)
# Encrypt a message
token = cipher_suite.encrypt(b'your_secure_token_here')
# Decrypt the message
api_token = cipher_suite.decrypt(token).decode()
print(f'Using API token: {api_token}')5. Secrets Management Services:
For highly sensitive or production environments, use secrets management tools like AWS Secrets Manager, Azure Key Vault, Google Cloud Secret Manager, or HashiCorp Vault. These services provide more robust security and management capabilities.
Summary
- Environment Variables and .env files: Simple and effective for many use cases.
- Keyring: Provides secure local storage using OS capabilities.
- Encrypted Files: Good for storing multiple secrets securely.
- Secrets Management Services: Best for cloud-based, production-grade applications.
Choose the method that best fits your security requirements and deployment environment.

That’s all folks!
Thanks!
Related Posts
00#Episode#PurePythonSeries — Lambda in Python — Python Lambda Desmistification
01#Episode#PurePythonSeries — Send Email in Python — Using Jupyter Notebook — How To Send Gmail In Python
02#Episode#PurePythonSeries — Automate Your Email With Python & Outlook — How To Create An Email Trigger System in Python
03#Episode#PurePythonSeries — Manipulating Files With Python — Manage Your Lovely Photos With Python!
04#Episode#PurePythonSeries — Pandas DataFrame Advanced — A Complete Notebook Review
05#Episode#PurePythonSeries — Is This Leap Year? Python Calendar — How To Calculate If The Year Is Leap Year and How Many Days Are In The Month
06#Episode#PurePythonSeries — List Comprehension In Python — Locked-in Secrets About List Comprehension
07#Episode#PurePythonSeries — Graphs — In Python — Extremely Simple Algorithms in Python
08#Episode#PurePythonSeries — Decorator in Python — How To Simplifying Your Code And Boost Your Function
10#Episode#PurePythonSeries — CS50 — A Taste of Python — Harvard Mario’s Challenge Solver \o/
11#Episode#PurePythonSeries — Python — Send Email Using SMTP — Send Mail To Any Internet Machine (SMTP or ESMTP)
12#Episode#PurePythonSeries — Advanced Python Technologies — qrcode, Speech Recognition in Python, Google Speech Recognition
13#Episode#PurePythonSeries — Advanced Python Technologies II — qFace Recognition w/ Jupyter Notebook & Ubuntu
14#Episode#PurePythonSeries — Advanced Python Technologies III — Face Recognition w/ Colab
15#Episode#PurePythonSeries — ISS Tracking Project — Get an Email alert when International Space Station (ISS) is above of us in the sky, at night
16#Episode#PurePythonSeries — Using Gemini Chat on Collab — Random Number Generation, List Manipulation & Rock-Paper-Scissors Game Implementations
17#Episode#PurePythonSeries — Python — Basics — Functions, OOP, file handling, calculator, loops
18#Episode#PurePythonSeries — Python — Efficient File Handling in Python — Best Practices and Common Methods (this one)
19#Episode#PurePythonSeries — Python — How To Securely Save Credentials in Python — Like API tokens, passwords, or other sensitive data (this one)
Note
The command export API_TOKEN='your_secure_token_here' is typically used in a shell script or a configuration file to set an environment variable. To use this in Python, you don't directly save this in a Python file, but rather in a file that initializes your environment before running your Python script.
Here are a few common options for where to save this command:
1. Shell Profile Files (Permanent Setting)
If you want to set the environment variable globally and persistently across sessions, you should add the command to your shell profile file. The specific file depends on your operating system and the shell you’re using:
- For
bashshell on Linux or macOS: Add to~/.bashrcor~/.bash_profile. - For
zshshell on macOS: Add to~/.zshrc. - For
bashshell on Windows (using Git Bash or WSL): Add to~/.bashrc. - For
PowerShellon Windows: Set a persistent environment variable using theEnvironmentPS drive.
Example for Linux/macOS using bash:
- Open your terminal.
- Edit the profile file (e.g.,
~/.bashrcor~/.bash_profile)
nano ~/.bashrc
Add the following line at the end of the file:
export API_TOKEN='your_secure_token_here'- Save the file and close the editor.
- Reload the file to apply the changes:
source ~/.bashrc2. Shell Script File (Temporary or Specific Session)
If you want to set the environment variable only for specific sessions or scripts, you can create a shell script:
- Create a new shell script file (e.g.,
set_env.sh):
nano set_env.sh
Add the export command to the script:
#!/bin/bash
export API_TOKEN='your_secure_token_here'- Save and close the file.
- Make the script executable:
chmod +x set_env.shRun the script before your Python script to set the environment variable:
source set_env.sh
python your_script.py3. .env File (Used with Python Libraries)
If you prefer to use a .env file with Python, the environment variables are stored there, and then loaded in your Python script using a library like python-dotenv.
- Create a
.envfile:
nano .envAdd your environment variable:
API_TOKEN='your_secure_token_here'Load the .env file in your Python script:
from dotenv import load_dotenv
import osload_dotenv() # Load variables from .env fileapi_token = os.getenv('API_TOKEN')
print(api_token) # Your secure token





