Load Credentials from Windows Environment Variables in Python
Keep passwords and API keys out of source code — read secrets from Windows environment variables with python-dotenv.
Introduction
It's very common that we store sensitive information like Email, Username, Password, API keys, etc. in our code as plain text. Thus, anyone can access and misuse that information, which is not good for anyone.
Another common case is when we run a script that was written by someone else, often the author doesn't want to store his credentials with the script. So it would be nice if the script takes the credentials of the individual who runs the code instead of using the author's credentials each time.
For similar reasons, it's always a good practice not to store sensitive information directly in our code.
Import Libraries
We will start by importing the necessary libraries. If any of the below libraries are not available on your system, you can install them by executing conda install library_name or pip install library_name in the command prompt.
import os
import re
import pandas as pd
import sqlalchemy as sqa
from snowflake.sqlalchemy import URLSet Enviornment Variables
In order to protect sensitive information without storing it in a script, you first have to store it as a system environment variable. The process itself is very simple, and you may follow any blog or video to get this step done. I found this video very straight-forward - Set Enviornment Variables - Windows.
Get Environment Variables
Once you follow the steps mentioned above in Set Environment Variables and finish setting up enviornment variables - USERACCOUNT_SNOWFLAKE, USERNAME_SNOWFLAKE, USERPASS_SNOWFLAKE and DATABASE_SNOWFLAKE you have to restart the operating system or you may get KeyError.
snowflake_engine = sqa.create_engine(URL(
account = os.environ['USERACCOUNT_SNOWFLAKE'],
user = os.environ['USERNAME_SNOWFLAKE'],
password = os.environ['USERPASS_SNOWFLAKE'],
database = os.environ['DATABASE_SNOWFLAKE']
))
snowflake_engineRead Data from Database
Now that everything is setup, we will read data from the database using the snowflake engine to test if things are working as expected.
query = """
SELECT * FROM TECHNICAL_BLOG_DB.PYTHON_SCHEMA.SUPERSTORE_YEARLY_DATA;
"""
df = pd.read_sql(sql = query, con = snowflake_engine, parse_dates = ['order_date', 'ship_date'])
df.head(2)df.info()Write Data into Database
As we have successfully read data from database let's try to write some data into database too.
path = os.getcwd()
subdirectory = 'data'
file = os.path.join(path, subdirectory, 'Databel - Data.csv')
filedf = pd.read_csv(file)
df.head(3)for col in df.columns:
df.rename(columns = {
col : re.sub('[^0-9a-zA-Z]+', '_', col).lower()
}, inplace = True)df.info()df.to_sql(
name = 'databel_data',
schema = 'python_schema',
con = snowflake_engine,
if_exists = 'replace',
index = False,
method = 'multi'
)print('Successfully inserted {0} rows in schema/table: {1}.{2}!'.format(df.shape[0], 'python_schema', 'databel_data'))Conclusion
So we have successfully completed the data read and write operations from and to the database. We've seen that by storing our credentials in Windows environment variables, our code still works as expected.
I hope you've learned a good practice to follow while scripting. Thank you so much for making it to the end, and I look forward to seeing you in another of my writings. Thank you!