Flask Snippets

Snippets are unofficial and unmaintained.

This is an archived view of user-submitted snippets. Despite being hosted on the Flask site, they are not official. No Flask maintainer has curated or checked the snippets for security, correctness, or design.

Configure SECRET_KEY from a file in the instance directory.

Posted by Simon Sapin on 2012-12-11 @ 14:04 and filed in APIs and Microformats

import sys
import os.path

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)
        app.config['SECRET_KEY'] = open(filename, 'rb').read()
    except IOError:
        print 'Error: No secret key. Create it with:'
        if not os.path.isdir(os.path.dirname(filename)):
            print 'mkdir -p', os.path.dirname(filename)
        print 'head -c 24 /dev/urandom >', filename

Usage example, after deploying to a new machine:

$ ./run.py
Error: No secret key. Create it with:
mkdir -p /home/simon/exampleapp/instance
head -c 24 /dev/urandom > /home/simon/exampleapp/instance/secret_key
# Copy-and-paste the two commands
$ ./run.py 
 * Running on
 * Restarting with reloader

This snippet by Simon Sapin can be used freely for anything you like. Consider it public domain.