0
votes

I have installed flask in a virtual environment as described here https://flask.palletsprojects.com/en/1.1.x/installation/#install-create-env

  • Create a directory and run python3 -m venv venv inside the directory to use virtual environment
  • Then source venv/bin/activate to activate the environment
  • Then pip install flask

Then I created a script like described here https://flask.palletsprojects.com/en/1.1.x/quickstart/

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Then I added export FLASK_APP=hello.py and ran python3 -m flask run which worked just fine

python3 -m flask run
 * Serving Flask app "hello.py"
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

But when I then change FLASK_ENV=development and run the same command I get an error

python3 -m flask run
 * Serving Flask app "hello.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
/usr/local/opt/python/bin/python3.7: No module named flask

I unset the FLASK_ENV and ran the same command again and everything works as when I did this the first time.

2

2 Answers

0
votes

Well, one solution might be to not set any environment variables and run Flask with just python.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run(debug=True)

and then you just activate the virtual environment by source env/bin/activate and then run python main.py.

You can also set the flask environment in your code by doing app.config['FLASK_ENV'] = 'development' but I wouldn't recommend it since if you're going to deploy your Flask app to platforms like Heroku or GCP, it's not going to work as intended.

0
votes

Another way would be for you to set your environment variables in a .flaskenv file in the root directory:

$ touch .flaskenv 

Then define your environment variables in .flaskenv:

FLASK_APP=main.py
FLASK_ENV=development
FLASK_DEBUG=True

Install python-dotenv to help with loading your environment variables:

$ pip3 install python-dotenv

On your terminal, run:

$ flask run

Auto reload should work every time you make a change to your application.