To directly answer your two questions:

  1. The secret keys are stored external to the source code so that they are not commit to revision control.
  2. The secret key isn't created by exporting the environment variable, nor is it created using the value in the environment variable.

The information you probably are really after:

First, keep in mind that I am not a cryptology expert! With that out of the way…

What you need to do is to generate some secret of appropriate size and cryptographic security for your application, then set the environment variable to be that value.

I'm making a guess that the secret key is being used in relation with the flask.ext.login.make_secure_token method of the Flask-Login module you linked to. If this is the case, looking at the source code, the key is being used with HMAC for a SHA-512. Ideally, the key should be the same as the blocksize used by the algorithm which, in this case, as indicated by the source for the Python 2.7 hmac implementation is 64 for 512-bit HMAC. If the key is smaller than the blocksize, it will be padded with zeros; if larger, it will hashed down to the blocksize.

The Flask quickstart documentation section for sessions provides an example backed up by Python's os.urandom documentation for generating crytographically suitable random bytes to use for the secret key. I would alter their example as we want a key for a blocksize of 64, rather than 24, to be:

import os
os.urandom(64)

Take the result of that and set the environment variable to the value. Using the Flask example directly (don't use these values for your code):

>>> import os
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'

You would take the output, and set the environment variable to that value:

export BLOGFUL_SECRET_KEY='\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
Answer from lagweezle on Stack Overflow
Top answer
1 of 2
4

To directly answer your two questions:

  1. The secret keys are stored external to the source code so that they are not commit to revision control.
  2. The secret key isn't created by exporting the environment variable, nor is it created using the value in the environment variable.

The information you probably are really after:

First, keep in mind that I am not a cryptology expert! With that out of the way…

What you need to do is to generate some secret of appropriate size and cryptographic security for your application, then set the environment variable to be that value.

I'm making a guess that the secret key is being used in relation with the flask.ext.login.make_secure_token method of the Flask-Login module you linked to. If this is the case, looking at the source code, the key is being used with HMAC for a SHA-512. Ideally, the key should be the same as the blocksize used by the algorithm which, in this case, as indicated by the source for the Python 2.7 hmac implementation is 64 for 512-bit HMAC. If the key is smaller than the blocksize, it will be padded with zeros; if larger, it will hashed down to the blocksize.

The Flask quickstart documentation section for sessions provides an example backed up by Python's os.urandom documentation for generating crytographically suitable random bytes to use for the secret key. I would alter their example as we want a key for a blocksize of 64, rather than 24, to be:

import os
os.urandom(64)

Take the result of that and set the environment variable to the value. Using the Flask example directly (don't use these values for your code):

>>> import os
>>> os.urandom(24)
'\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'

You would take the output, and set the environment variable to that value:

export BLOGFUL_SECRET_KEY='\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'
2 of 2
0

Didn't realize the actual command to set the secret key is:

export BLOGFUL_SECRET_KEY="your_secret_key_here"

And the key can be generated with something like this using the Python interpreter:

>>> import os
>>> os.urandom(24)
'\x072\xe7E|ns\x18g\x80& \xa3\xbf\xed\x91\xe6\x08+\x88\xd6\xafe['
🌐
Readthedocs
explore-flask.readthedocs.io › en › latest › configuration.html
Configuration — Explore Flask 1.0 documentation
# instance/config.py SECRET_KEY = 'Sm9obiBTY2hyb20ga2lja3MgYXNz' STRIPE_API_KEY = 'SmFjb2IgS2FwbGFuLU1vc3MgaXMgYSBoZXJv' SQLALCHEMY_DATABASE_URI= \ "postgresql://user:TWljaGHFgiBCYXJ0b3N6a2lld2ljeiEh@localhost/databasename" If the difference between your production and development environments are pretty minor, you may want to use your instance folder to handle the configuration changes. Variables defined in the instance/config.py file can override the value in config.py.
Discussions

Hiding secret keys in .env file
Yes, evironment variables are a common solution to this problem. I have not used Heroku, but I would assume it supports defining environment variables for deployments. You would not need a .env file as such, but the variables would exist in the environment that the server is running in. Side note - as gut tracks all history, you should be very careful about making your repo public that has had private keys committed in it. To be safe I would rotate your creds before the move More on reddit.com
🌐 r/flask
12
16
December 21, 2020
python - Where do I get SECRET_KEY for Flask? - Stack Overflow
While trying to set up Flask-Debugtoolbar, I am getting: ... Important to note: you should generate the secret key once and then copy/paste the value into your application or store it as an environment variable. More on stackoverflow.com
🌐 stackoverflow.com
I don't know how set SECRET_KEY
Hardcoding a fallback is bad. You may regret allowing a random string fallback later. More on reddit.com
🌐 r/flask
22
7
December 2, 2024
python - How to get Flask app to run locally after exporting secret key as an environment variable? - Stack Overflow
I then set app.config['SECRET_KEY'] = "secret-token-output-from-terminal-as-above" that enables the flask app to run smoothly. But as soon as I export SECRET_KEY (e.g., set it as an environment variable) and import os, the app does not work. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Flask
flask.palletsprojects.com › en › stable › config
Configuration Handling — Flask Documentation (3.1.x)
> $env:FLASK_SECRET_KEY = "5f352379324c22463451387a0aec5d2f" > $env:FLASK_MAIL_ENABLED = "false" > flask run * Running on http://127.0.0.1:5000/ The variables can then be loaded and accessed via the config with a key equal to the environment variable name without the prefix i.e.
🌐
Hackers and Slackers
hackersandslackers.com › configure-flask-applications
Configuring Your Flask App
September 30, 2018 - The simplest (not to be confused with "best") way to configure a Flask app is by defining config values as global variables in config.py: """Flask App configuration.""" # General Config ENVIRONMENT = "development" FLASK_APP = "my-app" FLASK_DEBUG = True SECRET_KEY = "GDtfD^&$%@^8tgYjD"
🌐
Reddit
reddit.com › r/flask › hiding secret keys in .env file
r/flask on Reddit: Hiding secret keys in .env file
December 21, 2020 -

I am not sure that this might be the correct subreddit, but if anyone could help or at least point me in the correct subreddit, it would be great!

So here it is. I have my website made from Flask and hosted on Heroku. Now the website uses google APIs and thus have a credentials.JSON file in my root folder.

Heroku is building the site from a git repository (is private due to the presence of the .JSON file). But I want to make it public and thus would be required to hide the credentials.JSON file in such a manner that GitHub ignores that file but Heroku doesn't.

I know it sounds ridiculous to do so, but when I asked my friend, he told me that I can store it as an environment variable in a .env file. Can anyone help how to achieve this? TIA

🌐
www.sethserver.com
sethserver.com › security › flask secret key generator: secure and free [2026]
Flask Secret Key Generator: Secure and Free [2026]
June 29, 2026 - Generate a secure Flask SECRET_KEY with Python's secrets module and store it safely in an environment variable. Free generator with a short setup guide.
Find elsewhere
🌐
Rustcodeweb
rustcodeweb.com › 2025 › 05 › flask-managing-environment-variables.html
Flask: Managing Environment Variables | RUSTCODE
May 31, 2025 - Flask’s configuration system, integrated with Jinja2 Templating for rendering and Werkzeug WSGI for request handling, supports environment variables to enhance security, maintainability, and deployment flexibility.
🌐
Stack Overflow
stackoverflow.com › questions › 72454048 › how-to-get-flask-app-to-run-locally-after-exporting-secret-key-as-an-environment
python - How to get Flask app to run locally after exporting secret key as an environment variable? - Stack Overflow
I then set app.config['SECRET_KEY'] = "secret-token-output-from-terminal-as-above" that enables the flask app to run smoothly. But as soon as I export SECRET_KEY (e.g., set it as an environment variable) and import os, the app does not work.
🌐
GitHub
github.com › mlflow › mlflow › issues › 12399
Allow setting app.secret_key from environment variable · Issue #12399 · mlflow/mlflow
June 18, 2024 - To ensure that user sessions are managed securely and consistently across multiple workers, we need to set a common app.secret_key. configuring the secret key through an environment variable, we can securely manage the key without hardcoding it, aligning with our security best practices.
Author   mlflow
🌐
Morgan VanYperen
morgvanny.com › home › securing your session key in flask
Securing Your Session Key in Flask - Morgan VanYperen
June 7, 2023 - 4. Create a file called .env in your flask server directory 5. In that file, put SECRET_KEY= and then paste the key you copied from the terminal. No spaces or quotes necessary. An example may look like SECRET_KEY=6050fb1f5f3d35b14484718c447b1424375a6bbd39150701c0ffb5db506eadb2 6. In whichever file app.secret_key is being set (could likely be app.py or config.py) add from os import environ and from dotenv import load_dotenv 7.
🌐
MoldStud
moldstud.com › articles › developers faq › flask developers questions › managing environment variables in flask applications
Managing Environment Variables in Flask Applications | MoldStud
October 22, 2024 - One common method is to use the os module in Python to access environment variables. Here is an example of how you can access an environment variable in your Flask application: import os SECRET_KEY = os.getenv('SECRET_KEY')
🌐
Flask Deployment Hub
flask-deployment.com › home › flask environment variables and secrets setup
Flask Environment Variables and Secrets Setup
Verify the running service sees the variables. ... sudo systemctl show myflaskapp --property=Environment sudo cat /proc/$(pgrep -f 'gunicorn.*myflaskapp' | head -n1)/environ | tr '\0' '\n' | grep -E 'FLASK_CONFIG|FLASK_DEBUG|DATABASE_URL|SECRET_KEY'
🌐
Snyk
snyk.io › blog › secure-python-flask-applications
How to secure Python Flask applications | Snyk
May 21, 2024 - However, generating the secret key is not enough. You also need to use it securely in your Flask app. The recommended secure way is to assign the secret key to an environment variable or use an encrypted configuration file and store the key there.
🌐
Prettyprinted
prettyprinted.com › tutorials › automatically_load_environment_variables_in_flask
Automatically Load Environment Variables in Flask
Unlike the values prepended with FLASK_ in our .flaskenv file, the variables in .env aren't meant to work for us automatically. Instead, we need to load them into our app. For that, we'll use the settings.py file. Inside of settings.py, let's import environ from os so we have access to our environment variables. ... Next, we need to assign those variables to Python variables, and then later we'll load them into our app. #demo/settings.py from os import environ SECRET_KEY = environ.get('SECRET_KEY') API_KEY = environ.get('API_KEY')
🌐
GeeksforGeeks
geeksforgeeks.org › python › flask-app-configuation
Flask App Configuation - GeeksforGeeks
June 4, 2026 - Flask provides a flexible configuration system that allows settings to be defined directly in code, loaded from external files, or managed through environment variables. 1. The simplest way to configure a Flask app is by directly assigning values to app.config: ... CONFIG_NAME: The name of the setting we want to define. Flask has built-in keys like DEBUG, SECRET_KEY and SQLALCHEMY_DATABASE_URI, but we can also create custom ones.
🌐
Reddit
reddit.com › r/flask › environment variables in flask & virtualenv
r/flask on Reddit: Environment variables in flask & virtualenv
April 4, 2017 -

I'm writing some of my first real-world code and have stumbled upon a project of setting up a simple Stripe payment gateway.

It's running fine locally using virtualenv when I launch it with

PUBLISHABLE_KEY=pk_test_co4ooReepa SECRET_KEY=sk_test_co4ooReepa python app.py

I've set up virtualenv in Webfaction following this guide and can get it working if I set the secret_key and publishable_key in the app.py which I know is unsanitary.

I therefore want to maintain the current code in app.py

Stripe_keys = {
    'secret_key': os.environ['SECRET_KEY'],
    'publishable_key': os.environ['PUBLISHABLE_KEY']
}

and pass in the environment variable.

I've tried putting them in httpd.conf using SetEnv with no luck.

I've tried appending them to virtualenv's bin/activate with no luck.

Apache just continually throws me this error

	[wsgi:error] mod_wsgi (pid=10968): Target WSGI script '/home/myname/webapps/myapp/htdocs/index.py' cannot be loaded as Python module.
[wsgi:error] mod_wsgi (pid=10968): Exception occurred processing WSGI script '/home/myname/webapps/myapp/htdocs/index.py'.
[wsgi:error] Traceback (most recent call last):
[wsgi:error]   File "/home/myname/webapps/myapp/htdocs/index.py", line 17, in <module>
[wsgi:error]     from app import app as application
[wsgi:error]   File "/home/myname/webapps/myapp/src/app.py", line 6, in <module>
[wsgi:error]     'secret_key': os.environ['SECRET_KEY'],
[wsgi:error]   File "/usr/local/lib/python3.5/os.py", line 725, in __getitem__
[wsgi:error]     raise KeyError(key) from None
[wsgi:error] KeyError: 'SECRET_KEY'

What am I doing dumb?