From 86aedf7ec533604df369afcfb96ce0a84ba4f4ad Mon Sep 17 00:00:00 2001 From: Farhan Ahmed Date: Wed, 26 Mar 2014 11:10:35 -0700 Subject: [PATCH] Minor update to how the secret key is generated in the production environment. --- Large-app-how-to.md | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/Large-app-how-to.md b/Large-app-how-to.md index 9fdef03..de4c9a0 100644 --- a/Large-app-how-to.md +++ b/Large-app-how-to.md @@ -97,7 +97,7 @@ We'll create 4 modules, a user module (manage user's registration, login, lost p DEBUG = False ADMINS = frozenset(['youremail@yourdomain.com']) - SECRET_KEY = 'SecretKeyForSessionSigning' + SECRET_KEY = 'This string will be replaced with a proper key in production.' SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(_basedir, 'app.db') DATABASE_CONNECT_OPTIONS = {} @@ -402,6 +402,9 @@ Finally, a simple `/app/templates/users/profile.html`: Here is the `/app/__init__.py` : ```python + import os + import sys + from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy @@ -410,6 +413,32 @@ Here is the `/app/__init__.py` : db = SQLAlchemy(app) + ######################## + # Configure Secret Key # + ######################## + def install_secret_key(app, filename='secret_key'): + """Configure the SECRET_KEY from a file + in the instance directory. + + If the file does not exist, print instructions + to create it from a shell with a random key, + then exit. + """ + filename = os.path.join(app.instance_path, filename) + + try: + app.config['SECRET_KEY'] = open(filename, 'rb').read() + except IOError: + print('Error: No secret key. Create it with:') + full_path = os.path.dirname(filename) + if not os.path.isdir(full_path): + print('mkdir -p {filename}'.format(filename=full_path)) + print('head -c 24 /dev/urandom > {filename}'.format(filename=full_path)) + sys.exit(1) + + if not app.config['DEBUG']: + install_secret_key(app) + @app.errorhandler(404) def not_found(error): return render_template('404.html'), 404