Using the .env File
00:00
So this lesson is optional. I’ll be showing you how to use the .env file, but you don’t have to do that. I personally didn’t do that. I used my configuration file for my shell because I’m on Linux.
00:12
But if you want to use the .env file, firstly, you’ll have to set it up. In other words, you’ll have to create a .env file in the root of your project.
00:22
And then you add OPENAI_API_KEY to that .env file. Again, you need to spell the environment variable name correctly. So OPENAI_API_KEY, all in uppercase, and then equals, and then between quotation marks, your API key.
00:44
Secondly, you’ll actually have to adjust your Python code. So that’s why we needed the virtual environment to exist first. So you’ll need to install a library called python-dotenv.
00:56 And then you need to add two lines of code to your project.
01:01
So to install python-dotenv, again, it depends on your operating system. So on Linux and Mac, it’s python -m pip install python-dotenv, or python3 for certain Linux distros.
01:17
And for Windows PowerShell, it’s python -m pip install python-dotenv. So then you need to add code to your project because you need to load the variables from the .env file into the system environment.
01:34
So you need to add these two lines of code. So from dotenv import load_dotenv, and then load_dotenv() with parentheses, and nothing between the parentheses.
01:48
That code will then make sure that your environment variables that live in your .env file are now in the system environment. You’ll need to add this code to the course code. So if you’ve downloaded the code from the course, these two lines are not in there because as I said, I didn’t use the .env file.
02:08 And then also remember to please never hard-code your API key directly into your Python scripts or commit it to version control. I told you I was going to repeat this.
02:19
So therefore, immediately add the .env file to your .gitignore file. So that’s to avoid your .env file being committed to version control.
02:33
Right. So with all that done, the next step is then to install the actual openai package in the next lesson.
Become a Member to join the conversation.
