Skip to content
Advertisement

How to securely pass credentials in python?

Passing login credentials into a python script for a website. However, I want the credentials to not be stored as plaintext in the .py files. How can I securely store the login credentials in a .py file so it can use them to login?

Advertisement

Answer

You can use an environmental file in your project root directory and load in the variables from this file during runtime, in Python you can do this with the python-dotenv package.

$ pip install python-dotenv

credentials.py File:

import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv()) # Load the .env file.

# Fetch variables from the .env file.
account_username = os.getenv("ACCOUNT_USERNAME")
account_password = os.getenv("ACCOUNT_PASSWORD")

.env File:

ACCOUNT_USERNAME = SomeUser
ACCOUNT_PASSWORD = somestrongpassword123

And from there, you can use the account_username and account_password as normal to authenticate and login to the website.


Security notice: Be sure to add the .env file to your .gitignore so you avoid pushing your environmental file to version control.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement