Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I place the secret key in Flask?

Tags:

python

flask

While reading exploreflask.com, I learned that it is best practice to use two different config files, one for development and one for production. I don't understand whether to place the secret key inside of the development or production config.

The private nature of the instance folder makes it a great candidate for defining keys that you don’t want exposed in version control. These may include your app’s secret key or third-party API keys.

I suppose the secret key shouldn't be shared. Should I put the secret key in the development config or the production config, or should I have a different key for each config?

like image 314
Pav Sidhu Avatar asked Jun 16 '15 16:06

Pav Sidhu


People also ask

Do I need a secret key for Flask?

Each Flask web application contains a secret key which used to sign session cookies for protection against cookie data tampering. It's very important that an attacker doesn't know the value of this secret key.

How long should a secret key be Flask?

It requires some fundamental breakthroughs in physics and our understanding of the universe. So following the docs: size of 24 bytes and generating it randomly you should be fine.

What happens if a Flask server secret key is changed?

The secret key is used to sign the session cookie. If you had to restart your application, and regenerated the key, all the existing sessions would be invalidated.


2 Answers

Place a secret key in the development config, which gets committed to the repo. This is convenient for developers, because they don't have to generate one to start running the app. In production, use a production config (which is never committed to the repo), with a unique secret key. The production config should override the development config.

app = Flask(__name__, instance_relative_config=True)
# default value during development
app.secret_key = 'dev'
# overridden if this file exists in the instance folder
app.config.from_pyfile('config.py', silent=True)

If you don't have a way to add private files in production, such as on Heroku, another option is to use environment variables. If the variable is set, it overrides the default.

app.secret_key = os.environ.get('SECRET_KEY', 'dev')
like image 81
davidism Avatar answered Oct 10 '22 23:10

davidism


I use a mixture of hardcoded values and environment variables in my production config.py:

import os


class Config(object):
    SECRET_KEY = os.environ.get("SECRET_KEY")
    SQLALCHEMY_DATABASE_URI = os.environ.get("DB_PROD")
    SQLALCHEMY_TRACK_MODIFICATIONS = False

In my development config.py, eveything is hardcoded.

like image 25
NMO Avatar answered Oct 10 '22 22:10

NMO