Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is adding Flask env vars to the virtualenv's activate script OK?

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.

like image 808
rjanke Avatar asked Mar 30 '18 17:03

rjanke


People also ask

How do you set environment variables in flask?

Command-line: Similarly, the FLASK_ENV variable sets the environment on which we want our flask application to run. For example, if we put FLASK_ENV=development the environment will be switched to development. By default, the environment is set to development.

How do I run an environment variable in a flask in Windows?

If you're on Windows 10, search "View Advanced System Settings." Then click environmental variables, hit new user variable and make it FLASK_APP and set the path where it asks. Then do flask run in terminal.

How do I know if my VENV is active?

Note: Before installing a package, look for the name of your virtual environment within parentheses just before your command prompt. In the example above, the name of the environment is venv . If the name shows up, then you know that your virtual environment is active, and you can install your external dependencies.

What is ENV flask?

The environment is used to indicate to Flask, extensions, and other programs, like Sentry, what context Flask is running in. It is controlled with the FLASK_ENV environment variable and defaults to production . Setting FLASK_ENV to development will enable debug mode.


1 Answers

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.

like image 94
davidism Avatar answered Sep 22 '22 02:09

davidism