[Tutor] Environment variables and Flask

Mats Wichmann mats at wichmann.us
Fri Jun 28 09:22:07 EDT 2019


On 6/27/19 11:24 PM, Mayo Adams wrote:
> I have for some time been flummoxed as to the significance of setting
> environment variables, for example in order to run a Flask application.
> What are these environment variables, exactly, and why is it necessary to
> set them? "Googling" here simply leads me into more arcana, and doesn't
> really help.

As others have noted, it's a way to pass information from one process to
another at startup time.   Since this is a Python list, I thought it
might be instructive to show how it works. In Python, you access these
environment variables through a dictionary in the os module, called
environ, which "survives" across the call-another-process boundary,
unlike any normal variables you might set in your program. Here's a
trivial Python app that is able to recognize those environment variables
that begin with MYENV_.  That points up one issue with environment
variables right away: it's a namespace you share with everybody, and
there's a chance someone accidentally is using a variable you think is
important - because it's important to them in their context, not yours.
So tricks like special naming conventions may be useful.

In this snip, we build a dictionary from os.environ, using only the keys
that seem to be "for us":


=== child.py ===
import os

myenv = { k: v for k, v in os.environ.items() if "MYENV_" in k }

print("child found these settings:", myenv)
======

Now write another script which sets a value, then calls the child
script; then sets a different value, then calls the child script.

=== parent.py ===
import os
import subprocess

print("Calling with MYENV_foo set")
os.environ['MYENV_foo'] = "Yes"
subprocess.run(["python", "child.py"])

print("Calling with MYENV_bar set")
os.environ['MYENV_bar'] = "1"
subprocess.run(["python", "child.py"])
======



More information about the Tutor mailing list