Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting and retrieving environmental variables in flask applications

I want to build a very simple REST api using python3/flask.

Say for example I want to set my SECRET_KEY required by flask as env var.

What is the recommended way of going about it?

I am aware of python-dotenv package that allows (or should I say requires?) the .flaskenv file with env vars set as key-value pairs in the form of

SECRET_KEY="my_secret_key"
DB_NAME="mydatabase"

etc.

Then (I assume) I can create a settings.py file such as

import os
SECRET_KEY = os.getenv('SECRET_KEY`)

and then perform an import settings on my flask files and so on.

My main question is how can this be adapted in a containerized environment where there will not be such an .flaskenv file but the respective variables will be available as runtime env vars in the container itself (say via its orchestrator)

Will the above form of settings.py be able to retrieve env vars in the absence of .flaskenv?

like image 342
pkaramol Avatar asked Jun 10 '19 15:06

pkaramol


People also ask

What environment variable does Flask use?

It is controlled with the FLASK_ENV environment variable and defaults to production . Setting FLASK_ENV to development will enable debug mode. flask run will use the interactive debugger and reloader by default in debug mode.

How do you set environment variables?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables. Click New to create a new environment variable.


1 Answers

Set your environment variable in the interpreter:

export SECRET_KEY=123

Call the variable with environ.get():

from os import environ
from flask import Flask

app = Flask(__name__)

app.config['SECRET_KEY'] = environ.get('SECRET_KEY')

Verify:

@app.route('/verify')
def verify():
    return '<p>' + app.config['SECRET_KEY'] + '</p>'
like image 66
Gabe H. Avatar answered Oct 27 '22 22:10

Gabe H.