6

I'm working on my Flask project in a virtualenv. Every time I start a new terminal, I have to reinitialize these Flask environment variables:

export FLASK_APP="server.py"
export FLASK_DEBUG="1"

My goal is to not have to type them in manually.

I tried writing a Python script that set them, but couldn't make it work. I tried writing a shell script that set them, but Flask would raise an error that said my Python path was incorrect.

Finally, I tried adding the the env vars to the bottom of the virtualenv's activate script. It worked! The env vars are set and Flask runs as expected.

$ source venv/bin/activate
$ flask run

Is it OK to modify the activate script like this? This is just for development purposes.

davidism
  • 121,510
  • 29
  • 395
  • 339
rjanke
  • 63
  • 1
  • 5

2 Answers2

14

Yes, setting environment variables in the virtualenv's activate script is fine for managing your development environment. It's described in Flask's docs. They're only active when the env is activated in the terminal, and you have to remember to add them if you create a new env, but there's nothing wrong with it.


With Flask 1.0, you can use dotenv files instead. Install python-dotenv:

pip install python-dotenv

Add a .flaskenv file:

FLASK_APP=server

And the flask command will automatically set them when running a command:

flask run

The advantage of this over messing with the venv is that you can commit this file so it applies anywhere you work on the code.

davidism
  • 121,510
  • 29
  • 395
  • 339
2

Modifying venv/bin/activate file is working for you because the environment variable is getting defined inside the virtual environment. When you're using python3 -m venv venv the environment variables are not present in the new virtual environment. Instead of modifying the activate file, you can instead make a shell script which:

  1. Runs venv/bin/activate
  2. Defines the environment variables
  3. Runs the server

First, I tried writing a Python script that set them, but after research, I realized it was not possible(?).

You could use os.environ to do the same from within, but a shell script is better.