Dealing with passwords
Dealing with passwords#
OPTIONAL
This section is optional as we have already seen a different way of dealing with passwords here in section ipython-sql
lecture 2
We will make use of a python package dotenv. Install python package
%%sh
conda install -c anaconda python-dotenv
See also
https://anaconda.org/conda-forge/python-dotenv
This package looks for a .env file in the folder where your notebook resides, and it loads your database connection details to the environment variable for your session. Here is how my env file looks like
(base) ggeorg02@MacBook-Pro assign1 % cat .env
DB_HOST=mbandtweet.xxxxx.us-west-2.rds.amazonaws.com
DB_NAME=postgres
DB_USER=postgres
DB_PASS=password
DB_PORT=5432
You have to change this to your connection details To create a .env file, you might want to use your terminal. Check how to use vi editor
cd <path to your notebook folder>
vi .env
Note
I purposely created this file with just an extension, not a filename. And you can usually make this kind of file only from the terminal, so I am using vi editor. You might not be able to find this file from your file explorer, and that’s the reason we created it starting with a period. This means that .iamasecretfile
. So no wonder why you can’t see, right? This way, no one can accidentally look at this file when using your computer. if you want to see it, then again, you want to go to terminal and type ls -a
After this, you can call all variables like this.
import os
import psycopg2
##Make sure you import and load your .env file
from dotenv import load_dotenv
load_dotenv()
conString = {'host':os.environ.get('DB_HOST'),
'dbname':os.environ.get('DB_NAME'),
'user':os.environ.get('DB_USER'),
'password':os.environ.get('DB_PASS'),
'port':os.environ.get('DB_PORT')}
print(conString["port"])
Important
Make sure you close the cursor and connection before quitting your jupyter notebook. This is a good practice and can protect you from memory leakage and too many open connections.
cur.close()
conn.close()