Load Environment Variables From .env Files in Python

NeuralNine · Intermediate ·⚡ Algorithms & Data Structures ·3y ago

Key Takeaways

The video demonstrates how to use the Python dotenv module to load environment variables from .env files in Python.

Full Transcript

what is going on guys welcome back in today's video we're going to learn about the python.nf module or package which allows us to load key value pairs from a file and set them as environment variables which is the best practice way to handle uh configurations and especially sensitive information like API keys and passwords so let us get right into it [Music] alright so we're going to learn about the python-enf package in this video today I just recently made a video where I used this package where I showed you guys how to properly store manage and load API keys in Python now you don't have to watch that video as a prerequisite here I'm just mentioning this on the side the proper way the professional way to do that we learned was to use environment variables so if you want to store a secret key some authentication Keys some credentials uh the professional way quote unquote is to do that with environment variables and you can load dot end files into your environment or also just as configuration dictionaries using this package and we're going to talk a little bit more about some specifics here today so what we want to do first is you want to open up your command line if you want to say pip install python-enf and then basically we're going to just use two functions here from this package and those two functions are going to be the load.n function and the dot nth values function so we're going to say here from Dot N import load Dot N and Dot and values and the difference here is just that we're using the Dot N file and we're either loading the key value pairs as environment variables for this particular run now or we're loading them as a dictionary so depending on the use case this makes uh sense so one or the other makes more sense now when you go to the package page so when you go to the Pi Pi or Pi Pi org page you can see here that they basically say it's a package that reads key value pairs from a Dot N file it helps in the development of applications following the 12 Factor principles and you can click on that and you can see here that one of them is config so one of the factors is config store config in the environment so this is basically what they're referring to at least that's what I assume and um yeah so basically you have a simple dot end file here we're going to create this here dot end and here now we can store all sorts of key value pairs so what we did in the one video and again it's not a prerequisite I'm just mentioning it for the people that saw it uh is we had something like my secret key is and then something some authentication key to some application or service um and then what you can do is you can just go into your python file you can say load.inf and then you can use the OS module which is a core python module to do something with it in this case we can say of get INF and then just my secrets key and then you're going to get this year now the good thing is that you can commit the whole code base of course you should always add this uh dot end file if it has sensitive information to the git ignore so you should never commit it to the repository um but essentially what you can do is you can just have the same application and all the person that wants to run the script has to do is is they have to create this dot end file they have to specify uh all sorts of keys configurations and stuff like that and then they can just run the script with the environment variables here or using the environment variables here um but what we can also do is we can do some more complicated stuff I mean it's not really complicated but it's a more more advanced stuff maybe so for example we can say here we have host and the host is going to be localhost in this case and we're going to have a port which is going to be let's say 9999 and then we can say combined if you want to call it that is equal to and then we can now refer to the variables we already have here in the environment we can say that the combination is dollar and then curly brackets inside of this we're going to say host then colon and then again dollar curly brackets port so that would also be some something that we can do so I can print now os.getn combined and then we get this combination result here and we can do that with different things so for example I could say also the mail is office at dollar host or maybe you would want to use the domain for this but the basic idea is that if you have for example some domain some host some some identifier here and all these other values depend on it you can also in the environment variable file in the dot end file you can also just refer to it so that you have to change it only once so right now if I print mail we can see I got office at localhost but I can also of course change this to neural9.com for example and then you can see office neural9.com and this mail does not exist by the way so you don't have to send messages to it um so that is the the way to just load everything into the environment now I also mentioned this in the other video already you can now overwrite environment variables that already exist or you can just um prefer them so if you have for example if I have on my system some key called my key and I have also my key in the environment file in the dot end file it's going to keep the environment verbal from my system however if I say overwrite equals true it's going to override the system environment variable and it's going to prefer the one that I specify in the file so this is just an important keyword here and now to the other function you can also load all of this not as an environment variable if you don't want to you can also load this as a dictionary so for example we can say here let's delete all this config equals Dot and values and then dot end the file and then we can just print the config here so you can see I have an ordered dictionary with my secret key host port and stuff like that and then of course I can also access individual keys for example my secret key there you go but again we don't have to commit the file we can just commit the code and the people have then to create their own environment file or you can somehow give it to them in a secure way offline or something on a flash drive and then delete it from the flash drive and then they only have it under system the important thing is that you don't commit a file you don't publish a file where you have sensitive information right um and now finally what I want to show you here is some Advanced way to and this is actually taken here from the documentation page or from the from the package page here uh is you can also have different environment files this is a use case maybe if you want to publish one of the files and the other one has sensitive information so you don't want to publish it uh what you can do is you can create a dot in dot shared is what they call it on the package page and then you can also create a not a python file actually just a file Dot and Dot Secret and then we can take for example the secret key and we can paste it into the secret file here and then we can take all this information and we can paste it into the shared file uh and then what we want to do is we want to create a convict file based on that so we can say that we want to have a dictionary and what we want to do is we want to say dot end values from Dot and shared now since this in and of itself is a dictionary and we want to pass it into the dictionary that we already have we need to unpack the values using these two stars here we're going to do the same thing for the secret file so basically we're now loading all the environment variables here or we're loading all the files from the dot and all the values all the key value pairs from The Dot N file and then optionally what you can do is you can also say unpack OS dot Environ which is going to give you the environment variables from the system now in my case I'm not going to do this here because I don't want to show all my environment variables but if I run this now and if I just run config you can see that we still have all the information here and this is also the case if I delete the environment file and the idea now would be to do it professionally would be to share the environment shared file and to keep the secret file secret so that only the people that know the actual keykin access this attribute but you can just publish this if it's not containing sensitive information so this is a package that is um I would recommend using this if you are working with API keys or something because as you can see here as I already showed you when you go to 12 Factor you go to config it mentions here specifically that credentials to external services and stuff like that should be stored in environment variables and of course you want to stick to a best practice to the best practice guidelines and this is a package that allows you to do that so that's it for today's video I hope you enjoyed it and hope you learned something if so let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you in the next video and bye

Original Description

Today we go a little bit deeper into the Python dotenv module, which allows us to load environment variables from .env files. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎙 Discord: https://discord.gg/JU4xr8U3dm 🎵 Outro Music From: https://www.bensound.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches how to load environment variables from .env files in Python using the dotenv module. It's a crucial skill for any Python developer to keep sensitive information separate from code. By following this lesson, you'll learn how to use the dotenv module to load environment variables and keep your code organized.

Key Takeaways
  1. Install the dotenv module using pip
  2. Create a .env file with environment variables
  3. Load the environment variables using the dotenv module
  4. Access the environment variables in your Python code
💡 The dotenv module allows you to load environment variables from a .env file, keeping sensitive information separate from your code.

Related AI Lessons

Bloom Filters, Explained Properly
Learn how Bloom filters work and their benefits, including tiny memory and blazing speed, in exchange for potential false positives.
Dev.to · Daksh Gargas
Prefix Sums: The Preprocessing Trick That Makes Range Queries Instant
Learn how prefix sums enable instant range queries in arrays, boosting performance in various applications
Medium · Programming
I Thought I Was Ready for the Interview — Then One Simple Math Question Destroyed Me
A simple math question can destroy a developer's interview, highlighting the importance of being prepared for unexpected questions
Medium · Programming
Week 2(Day 10): LeetCode Two Pointers(slow & fast): Remove Duplicates from Sorted Array (Brute…
Learn to remove duplicates from a sorted array using the two pointers technique, improving from brute force to optimized solutions
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →