How to set environment variables in VSCode when running Flask app?

Viewed 18462

I have a Python Flask app and have lots of environment variables that I need to set when running my app. I normally run my app like so...

python3 -m app.py

I would like it so that I can set all the environment variables my app needs so that I do not need to export each time I reopen my terminal. It would be nice if it could be workspace-specific or project-specific.

I know other editors like Pycharm can do similar things and was wondering how to do this in VS Code?

1 Answers

For Flask apps, you can create a launch.json configuration that will run your Flask app using VS Code's debugger. VS Code's launch.json supports a number of options, including the setting of environment variables that your Flask app needs.

Start with installing the Python extension for VS Code, to add support for "debugging of a number of types of Python applications, which includes Flask. Then, follow the Flask Tutorial from the VS Code docs.

Basically, you'll need to create a launch.json file in your workspace's .vscode folder.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "run-flask-app",
            "type": "python",
            "request": "launch",
            "module": "flask",
            "env": {
                "FLASK_APP": "/path/to/app.py",
                "FLASK_ENV": "development",
                "FLASK_DEBUG": "0",
                "AAA": "value of AAA env var",
                "BBB": "value of BBB env var",
                "CCC": "value of CCC env var"
            },
            "args": [
                "run",
                "--no-debugger",
                "--no-reload"
            ],
            "jinja": true
        },
    ]
}

The env portion is where you set all the environment variables. By default, it includes the required FLASK_*-related variables because it uses the flask command line tool for running apps.

Here, as an example, I've also set custom AAA and BBB and CCC vars. You can access that from code as normal env vars:

@app.route('/test')
def root():
    aaa = os.environ.get("AAA")
    bbb = os.environ.get("BBB")
    ccc = os.environ.get("CCC")
    print(f'{aaa}, {bbb}, {ccc}')
    return f'{aaa}, {bbb}, {ccc}'

Then run it from the Debug panel:

run the code

Just hit the play button and you should be able to see the printed env values from the Terminal panel or from the browser after accessing the /test endpoint. (If you have multiple terminals, it should appear under the Python Debug Console).

result

Lastly, by saving the .vscode/launch.json file under the workspace folder, then it's workspace-specific, and it will only affect the runtime environment used to launch your Flask app.

Related