<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Max</title>
    <description>The latest articles on DEV Community by Max (@max_does_tech).</description>
    <link>https://dev.to/max_does_tech</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1480711%2F23342aa5-b084-463e-8faa-df197166dc1a.png</url>
      <title>DEV Community: Max</title>
      <link>https://dev.to/max_does_tech</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/max_does_tech"/>
    <language>en</language>
    <item>
      <title>Python Environment Variables (Env Vars): A Primer</title>
      <dc:creator>Max</dc:creator>
      <pubDate>Thu, 22 Aug 2024 13:58:21 +0000</pubDate>
      <link>https://dev.to/vonagedev/python-environment-variables-env-vars-a-primer-55pd</link>
      <guid>https://dev.to/vonagedev/python-environment-variables-env-vars-a-primer-55pd</guid>
      <description>&lt;p&gt;Python developers often deal with data they don't want anyone else to see, like API keys, API secrets, database names, etc.&lt;/p&gt;

&lt;p&gt;One way programmers store these secrets is in environment variables. In this article, you will learn everything you need to know about using environment variables in Python. We’ll show you how to set Python environment variables, how to get them, and the different ways you can keep all of your secrets safe. We’ll finish with a real-life example of how we use them here at Vonage.&lt;/p&gt;

&lt;p&gt;Use the links below to skip ahead in the article:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://developer.vonage.com/en/blog/python-environment-variables-a-primer#what-are-environment-variables" rel="noopener noreferrer"&gt;What are Environment Variables?&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.vonage.com/en/blog/python-environment-variables-a-primer#how-to-use-environment-variables-in-python" rel="noopener noreferrer"&gt;How to Use Environment Variables in Python&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.vonage.com/en/blog/python-environment-variables-a-primer#how-to-get-python-environment-variables" rel="noopener noreferrer"&gt;How to Get Python Environment Variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.vonage.com/en/blog/python-environment-variables-a-primer#how-to-set-python-environment-variables" rel="noopener noreferrer"&gt;How to Set Python Environment Variables&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.vonage.com/en/blog/python-environment-variables-a-primer#how-to-store-python-environment-variables-5-methods" rel="noopener noreferrer"&gt;How to Store Python Environment Variables (5 Methods)&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.vonage.com/en/blog/python-environment-variables-a-primer#bonus-using-environment-variables-with-external-apis" rel="noopener noreferrer"&gt;Bonus: Using Environment Variables with External APIs&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What are Environment Variables?
&lt;/h2&gt;

&lt;p&gt;Environment variables (sometimes called "env vars") are variables you store outside your program that can affect how it runs. For example, you can set environment variables that contain the key and secret for an API. Your program might then use those variables when it connects to the API.&lt;/p&gt;

&lt;p&gt;Storing your secrets in your environment instead of your source code has a few advantages:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Security: Environment variables help you safeguard sensitive data like API keys and passwords. For example, you may not want whoever downloads your source code access to an API key you are using.&lt;/li&gt;
&lt;li&gt;Configuration Management: With environment variables, it’s easy to store and manage configuration settings.&lt;/li&gt;
&lt;li&gt;Portability: You can adapt applications to different environments without code changes. For example, if your code behaves differently on different operating systems, you can use an environment variable to manage this.&lt;/li&gt;
&lt;li&gt;Testing and Debugging: Developers can simplify testing and debugging by adjusting environment variables rather than changing the code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;em&gt;In essence, environment variables allow you to change your program’s behavior without changing the program itself.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;You can store environment variables in your operating system, but there are other ways to use them that we will learn about shortly.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Use Environment Variables in Python
&lt;/h2&gt;

&lt;p&gt;To follow along with this tutorial, you’ll need to have Python installed on your machine. You can install Python by &lt;a href="https://www.python.org/downloads/" rel="noopener noreferrer"&gt;downloading it from the official Python website&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You get and set environment variables in Python using the built-in &lt;code&gt;os&lt;/code&gt; module.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Get Python Environment Variables
&lt;/h2&gt;

&lt;p&gt;You can view all of the environment variables in your program by saving the following code in a Python file and then running this Python program:&lt;/p&gt;

&lt;p&gt;Your Python interpreter should print out all your operating system's environment variables when running this code. You can access the different environment variables in &lt;code&gt;os.environ&lt;/code&gt; like a Python dictionary. Here are two ways to get environment variables with Python:&lt;/p&gt;

&lt;p&gt;The last two lines in your Python code above do the same thing: both get the &lt;code&gt;USER&lt;/code&gt; environment variable from your operating system. However, when you use the first way, Python throws an exception if it does not find the variable.&lt;/p&gt;

&lt;p&gt;A good practice is to use &lt;code&gt;os.environ['MY_ENVIRONMENT_VARIABLE']&lt;/code&gt; if the environment variable is required for your Python application to run and &lt;code&gt;os.environ.get('MY_ENVIRONMENT_VARIABLE')&lt;/code&gt; if it is optional.&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Set Environment Variables
&lt;/h2&gt;

&lt;p&gt;To set environment variables in Python, you can add them to the &lt;code&gt;os.environ&lt;/code&gt; object like you would with a dictionary. However, only strings are permitted, as these are passed directly to the shell your interpreter is running in.&lt;/p&gt;

&lt;p&gt;To update an environment variable, simply override it in the exact same way:&lt;/p&gt;

&lt;h2&gt;
  
  
  How to Store Python Environment Variables (5 Methods)
&lt;/h2&gt;

&lt;p&gt;There are different reasons that you might want to store environment variables, so there are also different ways to store them. Sometimes, you just need something to be set on your local machine, whereas in other cases, you might need to run your application in production - these use cases require different approaches!&lt;/p&gt;

&lt;p&gt;Below, we’ll show you five ways to store environment variables for Python:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Operating System Storage&lt;/li&gt;
&lt;li&gt;File Storage&lt;/li&gt;
&lt;li&gt;Cloud Storage&lt;/li&gt;
&lt;li&gt;Universal Secret Manager Storage&lt;/li&gt;
&lt;li&gt;CI/CD System Storage&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Store Environment Variables on Your Operating System
&lt;/h3&gt;

&lt;p&gt;Sometimes, you don’t want to create an environment variable through Python if you just want to set something quickly. Luckily, this can be done through the command line. The examples I’ll give here work for Unix-like systems (Mac, Linux, etc.), but if you’re using Windows, you can &lt;a href="https://developer.vonage.com/en/blog/%E2%80%8B%E2%80%8Bhttps://www.howtogeek.com/789660/how-to-use-windows-cmd-environment-variables/" rel="noopener noreferrer"&gt;learn how to get and set environment variables in this tutorial&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In the previous example, &lt;code&gt;USER&lt;/code&gt; was an environment variable set by your operating system, representing who is using your computer. Although your operating system creates this variable automatically, you can also create your own environment variables.&lt;/p&gt;

&lt;p&gt;You can see all the environment variables from your command line by opening up a command line and typing the following (on a Unix-like system):&lt;/p&gt;

&lt;p&gt;export&lt;/p&gt;

&lt;p&gt;This will give you a list of every environment variable that your command-line shell has access to.&lt;/p&gt;

&lt;p&gt;Here’s how to create an environment variable on your command line:&lt;/p&gt;

&lt;p&gt;export VONAGE_API=your_api&lt;/p&gt;

&lt;p&gt;This creates a variable called &lt;code&gt;VONAGE_API&lt;/code&gt; and sets its value to &lt;code&gt;your_api&lt;/code&gt;. You can print any variable’s value like this:&lt;/p&gt;

&lt;p&gt;echo $VONAGE_API&lt;/p&gt;

&lt;p&gt;When you run the code above, you’ll see &lt;code&gt;your_api&lt;/code&gt; as the output.&lt;/p&gt;

&lt;h3&gt;
  
  
  Store Environment Variables in Files
&lt;/h3&gt;

&lt;p&gt;When you create a new environment variable using your terminal/command line, it only exists for that session. When you close your terminal, the environment variable no longer exists. Often when you’re programming, you want your environment variables to persist so they can be used every time you run your code. One way to accomplish this is to store them in a file: for example, a &lt;code&gt;.env&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Let’s create an example project to demonstrate how to use a &lt;code&gt;.env&lt;/code&gt; file to store environment variables.&lt;/p&gt;

&lt;p&gt;First, use your terminal to create a new folder for this tutorial, move into it and create a &lt;code&gt;.env&lt;/code&gt; file inside:&lt;/p&gt;

&lt;p&gt;mkdir env_variables_tutorial cd env_variables_tutorial touch .env&lt;/p&gt;

&lt;p&gt;Add this line to your &lt;code&gt;.env&lt;/code&gt; file:&lt;/p&gt;

&lt;p&gt;VONAGE_API=your_api&lt;/p&gt;

&lt;p&gt;python3 -m venv venv . ./venv/bin/activate&lt;/p&gt;

&lt;p&gt;Now we’re inside a Python Virtual Environment, we can install the package we need.&lt;/p&gt;

&lt;p&gt;pip install python-dotenv&lt;/p&gt;

&lt;p&gt;Now, we can use the &lt;code&gt;dotenv&lt;/code&gt; module from this package to load environment variables from the &lt;code&gt;.env&lt;/code&gt; file to the environment Python can access with the &lt;code&gt;os&lt;/code&gt; module. Create a Python file with the following content:&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;load_dotenv&lt;/code&gt; function brings environment variables from the &lt;code&gt;.env&lt;/code&gt; file into &lt;code&gt;os.environ&lt;/code&gt;, which can then be used like any other environment variables set by your operating system.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to Store Environment Variables in the Cloud
&lt;/h3&gt;

&lt;p&gt;When you create software for production, you probably won't run it from your computer. Instead, you most likely will run your code on a server.&lt;/p&gt;

&lt;p&gt;That means you need to know how to set and get environment variables from wherever you run your code in production.&lt;/p&gt;

&lt;p&gt;Here is a list of cloud providers and where you can get more information about dealing with environment variables using them:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html" rel="noopener noreferrer"&gt;AWS&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://learn.microsoft.com/en-us/azure/app-service/configure-common?tabs=portal#application-settings" rel="noopener noreferrer"&gt;Azure Apps&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-python?tabs=asgi,application-level&amp;amp;pivots=python-mode-decorators#environment-variables" rel="noopener noreferrer"&gt;Azure Functions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://cloud.google.com/functions/docs/configuring/env-var" rel="noopener noreferrer"&gt;Google Cloud Functions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://devcenter.heroku.com/articles/config-vars" rel="noopener noreferrer"&gt;Heroku&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.docker.com/compose/environment-variables/set-environment-variables/" rel="noopener noreferrer"&gt;Dockerfile&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.docker.com/engine/reference/run/#env-environment-variables" rel="noopener noreferrer"&gt;Docker Run&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Store Environment Variables in CI/CD systems
&lt;/h3&gt;

&lt;p&gt;If you use cloud-based CI/CD systems such as GitHub Actions, CircleCI, Travis, or Jenkins, you can also store environment variables in their systems.&lt;/p&gt;

&lt;p&gt;If you’re using GitHub for your project, you can store environment variables in the settings for your repo by navigating to the "Settings" tab and setting API keys etc., in the "Secrets and variables" setting under "Security".&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv8p9rpflyw0paeuke4ot.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fv8p9rpflyw0paeuke4ot.png" alt="Screenshot of the Secrets and Variables menu in GitHub settings. The item labeled Actions is selected." width="449" height="314"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here, you can create a new repository secret by clicking the option and setting values. This will now be available in your GitHub Actions runs.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn2liabibq2j9fbkp27q2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn2liabibq2j9fbkp27q2.png" alt="Screenshot of the Actions secrets New secret page. VONAGE_API_SECRET is entered as the Name, and my-secret-api-key-to-use-vonage-applications is entered as the Secret." width="512" height="273"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There’s lots of information about &lt;a href="https://docs.github.com/en/actions/learn-github-actions/variables" rel="noopener noreferrer"&gt;setting up environment variables with GitHub Actions&lt;/a&gt;, as well as &lt;a href="https://circleci.com/docs/env-vars/" rel="noopener noreferrer"&gt;CircleCI&lt;/a&gt;, &lt;a href="https://docs.travis-ci.com/user/environment-variables/" rel="noopener noreferrer"&gt;Travis&lt;/a&gt; and &lt;a href="https://www.jenkins.io/doc/pipeline/tour/environment/" rel="noopener noreferrer"&gt;Jenkins&lt;/a&gt;, as well as information for other providers.&lt;/p&gt;

&lt;h3&gt;
  
  
  Store Environment Variables with a Universal Secrets Manager
&lt;/h3&gt;

&lt;p&gt;Storing your secrets in a &lt;code&gt;.env&lt;/code&gt; file persists your environment variables but does have some problems.&lt;/p&gt;

&lt;p&gt;For example, say you are on a team with ten people. Everyone is tracking their secrets in &lt;code&gt;.env&lt;/code&gt; files, and one of the secrets changes (say you get a new API key). In that case, ten people all have to update their &lt;code&gt;.env&lt;/code&gt; file, which is not very efficient.&lt;/p&gt;

&lt;p&gt;Or, what if you decide to switch from Heroku to AWS? In that case, you will have to learn how to deal with secrets on a new platform, which requires extra work.&lt;/p&gt;

&lt;p&gt;To solve these problems, some programmers use &lt;a href="https://www.doppler.com/" rel="noopener noreferrer"&gt;a universal secrets manager like Doppler&lt;/a&gt;. A universal secrets manager allows you to store your secrets in one place, so everyone on your team can access them.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe2v1tcwzc5y3ldzm867o.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe2v1tcwzc5y3ldzm867o.png" alt="Screenshot of multiple secrets managed in Doppler." width="512" height="317"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With a universal secrets manager, your secrets are independent of your local machine or a cloud provider, so you can bring them with you no matter where you run your code.&lt;/p&gt;

&lt;h2&gt;
  
  
  Bonus: Using Environment Variables with External APIs
&lt;/h2&gt;

&lt;p&gt;Sometimes, if you’re using an external API’s sample project or sample code snippets, tooling is provided by the owner/maintainer to make it easier to use. Often, you’ll need to use environment variables to get the tooling set up optimally.&lt;/p&gt;

&lt;p&gt;Here at Vonage, we make use of environment variables in &lt;a href="https://github.com/Vonage/vonage-python-code-snippets" rel="noopener noreferrer"&gt;our Python code samples&lt;/a&gt; for sending SMS, making phone calls, sending verification codes, checking fraud scores, and much more.&lt;/p&gt;

&lt;p&gt;Let’s say you want to use &lt;a href="https://developer.vonage.com/en/number-insight/overview" rel="noopener noreferrer"&gt;Vonage’s Number Insight API&lt;/a&gt; to get information about some phone numbers. In this case, you might want to use a &lt;a href="https://github.com/Vonage/vonage-python-code-snippets/blob/main/number-insight/ni-basic.py" rel="noopener noreferrer"&gt;code sample like this one&lt;/a&gt; to get things working quickly in Python.&lt;/p&gt;

&lt;p&gt;To use this sample code, first &lt;a href="https://developer.vonage.com/sign-up" rel="noopener noreferrer"&gt;create a Vonage account&lt;/a&gt; (don’t worry, it’s free!) to get an API key and secret to authenticate your API calls.&lt;/p&gt;

&lt;p&gt;Next, clone the repo at &lt;a href="https://github.com/Vonage/vonage-python-code-snippets/" rel="noopener noreferrer"&gt;https://github.com/Vonage/vonage-python-code-snippets/&lt;/a&gt;. Once this is done, create a new Python virtual environment and install the required dependencies with&lt;/p&gt;

&lt;p&gt;You should see information about the phone number you entered, meaning you used Vonage’s Number Insight API to look up the phone number from your environment variables, without needing to edit the Python file itself at all! This is a major advantage of using environment variables.&lt;/p&gt;

&lt;p&gt;deactivate # if the virtual environment from earlier is still active python3 -m venv venv . ./venv/bin/activate pip install -r requirements.txt&lt;/p&gt;

&lt;p&gt;Finally, rename the &lt;code&gt;.env.dist&lt;/code&gt; file to &lt;code&gt;.env&lt;/code&gt; and add your API key and secret to the file, as well as changing the value for &lt;code&gt;INSIGHT_NUMBER&lt;/code&gt; to be the number you want to look up. Now you’re ready to run the code with&lt;/p&gt;

&lt;p&gt;python number-insight/ni-basic.py&lt;/p&gt;

&lt;p&gt;You should see information about the phone number you entered, meaning you used Vonage’s Number Insight API to look up the phone number from your environment variables, without needing to edit the Python file itself at all! This is a major advantage of using environment variables.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final Thoughts
&lt;/h2&gt;

&lt;p&gt;Getting and setting environment variables is an essential part of creating production software. If you’ve completed this tutorial, you’re now familiar with how to get and set environment variables using Python.&lt;/p&gt;

&lt;p&gt;You also now understand your different options for storing your secrets: temporarily setting them using your OS, storing them in a .env file, keeping them in the cloud, and using a universal secrets manager. The method you use will depend on the circumstances of the project you are working on. If you want to read more, &lt;a href="https://developer.vonage.com/en/blog/using-private-keys-in-environment-variables" rel="noopener noreferrer"&gt;this post on using private keys in environment variables&lt;/a&gt; has more information.&lt;/p&gt;

&lt;p&gt;If you want to start using Vonage APIs, you can &lt;a href="https://developer.vonage.com/sign-up" rel="noopener noreferrer"&gt;sign up for a free developer account (with free credits!)&lt;/a&gt; If you have any questions about this tutorial, feel free to reach out to us on our &lt;a href="https://developer.vonage.com/en/community/slack" rel="noopener noreferrer"&gt;Vonage Community Slack&lt;/a&gt; and ask us over there or by &lt;a href="https://twitter.com/VonageDev" rel="noopener noreferrer"&gt;messaging us on X, previously known as Twitter&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now, go ahead and try using environment variables in your own Python projects!&lt;/p&gt;

</description>
      <category>python</category>
    </item>
  </channel>
</rss>
