Skip to content
Myr

clean up secret key docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

consistent key across docs and examples consistent key across tests, set in conftest

authored by David Lord · committed by David Lord · parent cce6e7d · Browse files · 15 files+41 added−79 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+41 added−79 removed

  • tests:+12 added−47 removed
  • other:+29 added−32 removed

15 files+41 added−79 removed

modified:docs/patterns/flashing.rst+1 added-1 removed
20 unmodified lines
21 from flask import Flask, flash, redirect, render_template, \22 request, url_for2324 app = Flask(__name__)25 app.secret_key = 'some_secret'25 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'2627 @app.route('/')28 def index():29 return render_template('index.html')
121 unmodified lines
modified:docs/tutorial/setup.rst+4 added-4 removed
31 unmodified lines
32 app = Flask(__name__) # create the application instance :)33 app.config.from_object(__name__) # load config from this file , flaskr.py3435 # Load default config and override config from an environment variable36 app.config.update(dict(36 app.config.update(37 DATABASE=os.path.join(app.root_path, 'flaskr.db'),38 SECRET_KEY='development key',38 SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/',39 USERNAME='admin',40 PASSWORD='default'41 ))41 )42 app.config.from_envvar('FLASKR_SETTINGS', silent=True)4344In the above code, the :class:`~flask.Config` object works similarly to a45dictionary, so it can be updated with new values.
30 unmodified lines
76method on the config object and provide it with an import name of a77module. Flask will then initialize the variable from that module. Note78that in all cases, only variable names that are uppercase are considered.7980The ``SECRET_KEY`` is needed to keep the client-side sessions secure.80The :data:`SECRET_KEY` is needed to keep the client-side sessions secure.81Choose that key wisely and as hard to guess and complex as possible.8283Lastly, add a method that allows for easy connections to the specified84database. ::
17 unmodified lines
modified:docs/api.rst+6 added-6 removed
101 unmodified lines
102103Sessions104--------105106If you have the :attr:`Flask.secret_key` set you can use sessions in Flask107applications. A session basically makes it possible to remember108information from one request to another. The way Flask does this is by109using a signed cookie. So the user can look at the session contents, but110not modify it unless they know the secret key, so make sure to set that111to something complex and unguessable.106If you have set :attr:`Flask.secret_key` (or configured it from107:data:`SECRET_KEY`) you can use sessions in Flask applications. A session makes108it possible to remember information from one request to another. The way Flask109does this is by using a signed cookie. The user can look at the session110contents, but can't modify it unless they know the secret key, so make sure to111set that to something complex and unguessable.112113To access the current session you can use the :class:`session` object:114115.. class:: session
711 unmodified lines
modified:docs/config.rst+4 added-4 removed
37 unmodified lines
38method::3940 app.config.update(41 DEBUG=True,42 SECRET_KEY='...'42 SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/'43 )4445.. admonition:: Debug Mode with the ``flask`` Script46
319 unmodified lines
366Here is an example of a configuration file::367368 # Example configuration369 DEBUG = False370 SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'370 SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'371372Make sure to load the configuration very early on, so that extensions have373the ability to access the configuration when starting up. There are other374methods on the config object as well to load from individual files. For a
9 unmodified lines
384385Environment variables can be set on Linux or OS X with the export command in386the shell before starting the server::387388 $ export SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'388 $ export SECRET_KEY='5f352379324c22463451387a0aec5d2f'389 $ export DEBUG=False390 $ python run-app.py391 * Running on http://127.0.0.1:5000/392 * Restarting with reloader...393394On Windows systems use the `set` builtin instead::395396 >set SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'396 >set SECRET_KEY='5f352379324c22463451387a0aec5d2f'397 >set DEBUG=False398399While this approach is straightforward to use, it is important to remember that400environment variables are strings -- they are not automatically deserialized
197 unmodified lines
modified:docs/quickstart.rst+10 added-13 removed
158 unmodified lines
159 :align: center160 :class: screenshot161 :alt: screenshot of debugger in action162163More information on using the debugger can be found in the `Werkzeug 163More information on using the debugger can be found in the `Werkzeug164documentation`_.165166.. _Werkzeug documentation: http://werkzeug.pocoo.org/docs/debug/#using-the-debugger167
555 unmodified lines
723 from flask import Flask, session, redirect, url_for, escape, request724725 app = Flask(__name__)726727 # Set the secret key to some random bytes. Keep this really secret!728 app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'729730 @app.route('/')731 def index():732 if 'username' in session:733 return 'Logged in as %s' % escape(session['username'])
16 unmodified lines
750 # remove the username from the session if it's there751 session.pop('username', None)752 return redirect(url_for('index'))753751 # set the secret key. keep this really secret:752 app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'753754The :func:`~flask.escape` mentioned here does escaping for you if you are755not using the template engine (as in this example).756757.. admonition:: How to generate good secret keys758759 The problem with random is that it's hard to judge what is truly random. And760 a secret key should be as random as possible. Your operating system761 has ways to generate pretty random stuff based on a cryptographic762 random generator which can be used to get such a key::759 A secret key should be as random as possible. Your operating system has760 ways to generate pretty random data based on a cryptographic random761 generator. Use the following command to quickly generate a value for762 :attr:`Flask.secret_key` (or :data:`SECRET_KEY`)::763764 >>> import os765 >>> os.urandom(24)766 '\xfd{H\xe5<\x95\xf9\xe3\x96.5\xd1\x01O<!\xd5\xa2\xa0\x9fR"\xa1\xa8'764 $ python -c 'import os; print(os.urandom(16))'765 b'_5#y2L"F4Q8z\n\xec]/'766768 Just take that thing and copy/paste it into your code and you're done.769767A note on cookie-based sessions: Flask will take the values you put into the768session object and serialize them into a cookie. If you are finding some769values do not persist across requests, cookies are indeed enabled, and you are770not getting a clear error message, check the size of the cookie in your page
76 unmodified lines
modified:examples/flaskr/flaskr/factory.py+1 added-1 removed
20 unmodified lines
2122 app.config.update(dict(23 DATABASE=os.path.join(app.root_path, 'flaskr.db'),24 DEBUG=True,25 SECRET_KEY='development key',25 SECRET_KEY=b'_5#y2L"F4Q8z\n\xec]/',26 USERNAME='admin',27 PASSWORD='default'28 ))29 app.config.update(config or {})
35 unmodified lines
modified:examples/minitwit/minitwit/minitwit.py+1 added-1 removed
20 unmodified lines
21# configuration22DATABASE = '/tmp/minitwit.db'23PER_PAGE = 3024DEBUG = True25SECRET_KEY = 'development key'25SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/'2627# create our little application :)28app = Flask('minitwit')29app.config.from_object(__name__)
227 unmodified lines
modified:flask/app.py+2 added-2 removed
219 unmodified lines
220 #: ``TESTING`` configuration key. Defaults to ``False``.221 testing = ConfigAttribute('TESTING')222223 #: If a secret key is set, cryptographic components can use this to224 #: sign cookies and other things. Set this to a complex random value224 #: sign cookies and other things. Set this to a complex random value225 #: when you want to use the secure cookie for instance.226 #:227 #: This attribute can also be configured from the config with the228 #: ``SECRET_KEY`` configuration key. Defaults to ``None``.228 #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.229 secret_key = ConfigAttribute('SECRET_KEY')230231 #: The secure cookie uses this for the name of the session cookie.232 #:
1951 unmodified lines
modified:tests/static/config.json+1 added-1 removed
1{2 "TEST_KEY": "foo",3 "SECRET_KEY": "devkey"3 "SECRET_KEY": "config"4}
modified:tests/conftest.py+1 added-6 removed
16 unmodified lines
171819class Flask(_Flask):20 testing = True21 secret_key = __name__21 secret_key = 'test key'2223 def make_response(self, rv):24 if rv is None:25 rv = ''26 return super(Flask, self).make_response(rv)232824@pytest.fixture25def app():26 app = Flask(__name__)27 return app
141 unmodified lines
modified:tests/test_basic.py+2 added-22 removed
218 unmodified lines
219 assert client.get('/foo/bar').data == b'bar'220221222def test_session(app, client):223 app.secret_key = 'testkey'224223 @app.route('/set', methods=['POST'])224 def set():225 flask.session['value'] = flask.request.form['value']226 return 'value set'
7 unmodified lines
234235236def test_session_using_server_name(app, client):237 app.config.update(240 SECRET_KEY='foo',238 SERVER_NAME='example.com'239 )240241 @app.route('/')
7 unmodified lines
249250251def test_session_using_server_name_and_port(app, client):252 app.config.update(256 SECRET_KEY='foo',253 SERVER_NAME='example.com:8080'254 )255256 @app.route('/')
7 unmodified lines
264265266def test_session_using_server_name_port_and_path(app, client):267 app.config.update(272 SECRET_KEY='foo',268 SERVER_NAME='example.com:8080',269 APPLICATION_ROOT='/foo'270 )271
19 unmodified lines
291 return self.app(environ, start_response)292293 app.wsgi_app = PrefixPathMiddleware(app.wsgi_app, '/bar')294 app.config.update(300 SECRET_KEY='foo',295 APPLICATION_ROOT='/bar'296 )297298 @app.route('/')
6 unmodified lines
305306307def test_session_using_session_settings(app, client):308 app.config.update(315 SECRET_KEY='foo',309 SERVER_NAME='www.example.com:8080',310 APPLICATION_ROOT='/test',311 SESSION_COOKIE_DOMAIN='.example.com',312 SESSION_COOKIE_HTTPONLY=False,
15 unmodified lines
328329330def test_session_localhost_warning(recwarn, app, client):331 app.config.update(339 SECRET_KEY='testing',332 SERVER_NAME='localhost:5000',333 )334335 @app.route('/')
8 unmodified lines
344345346def test_session_ip_warning(recwarn, app, client):347 app.config.update(356 SECRET_KEY='testing',348 SERVER_NAME='127.0.0.1:5000',349 )350351 @app.route('/')
6 unmodified lines
358 w = recwarn.pop(UserWarning)359 assert 'cookie domain is an IP' in str(w.message)360361371def test_missing_session():372 app = flask.Flask(__name__)362def test_missing_session(app):363 app.secret_key = None364365 def expect_exception(f, *args, **kwargs):366 e = pytest.raises(RuntimeError, f, *args, **kwargs)367 assert e.value.args and 'session is unavailable' in e.value.args[0]
5 unmodified lines
373374375def test_session_expiration(app, client):376 permanent = True386 app.secret_key = 'testkey'377378 @app.route('/')379 def index():380 flask.session['test'] = 42
23 unmodified lines
404 assert match is None405406407def test_session_stored_last(app, client):418 app.secret_key = 'development-key'419408 @app.after_request409 def modify_session(response):410 flask.session['foo'] = 42411 return response
6 unmodified lines
418 assert client.get('/').data == b'42'419420421def test_session_special_types(app, client):434 app.secret_key = 'development-key'422 now = datetime.utcnow().replace(microsecond=0)423 the_uuid = uuid.uuid4()424425 @app.route('/')
23 unmodified lines
449 assert s['di_tag'] == {' di': 'not-a-dict'}450451452def test_session_cookie_setting(app):466 app.secret_key = 'dev key'453 is_permanent = True454455 @app.route('/bump')456 def bump():
33 unmodified lines
490 run_test(expect_header=False)491492493def test_session_vary_cookie(app, client):508 app.secret_key = 'testkey'509494 @app.route('/set')495 def set_session():496 flask.session['test'] = 'test'497 return ''
47 unmodified lines
545 expect('/no-vary-header', None)546547548def test_flashes(app, req_ctx):565 app.secret_key = 'testkey'566549 assert not flask.session.modified550 flask.flash('Zap')551 flask.session.modified = False552 flask.flash('Zip')
7 unmodified lines
560 # Specifically, if app.testing is not set to True, the AssertionErrors561 # in the view functions will cause a 500 response to the test client562 # instead of propagating exceptions.563582 app.secret_key = 'testkey'583564 @app.route('/')565 def index():566 flask.flash(u'Hello World')567 flask.flash(u'Hello World', 'error')
1265 unmodified lines
modified:tests/test_config.py+7 added-6 removed
17 unmodified lines
181920# config keys used for the TestConfig21TEST_KEY = 'foo'22SECRET_KEY = 'devkey'22SECRET_KEY = 'config'232425def common_object_test(app):26 assert app.secret_key == 'devkey'26 assert app.secret_key == 'config'27 assert app.config['TEST_KEY'] == 'foo'28 assert 'TestConfig' not in app.config2930
18 unmodified lines
4950def test_config_from_mapping():51 app = flask.Flask(__name__)52 app.config.from_mapping({53 'SECRET_KEY': 'devkey',53 'SECRET_KEY': 'config',54 'TEST_KEY': 'foo'55 })56 common_object_test(app)5758 app = flask.Flask(__name__)59 app.config.from_mapping([60 ('SECRET_KEY', 'devkey'),60 ('SECRET_KEY', 'config'),61 ('TEST_KEY', 'foo')62 ])63 common_object_test(app)6465 app = flask.Flask(__name__)66 app.config.from_mapping(67 SECRET_KEY='devkey',67 SECRET_KEY='config',68 TEST_KEY='foo'69 )70 common_object_test(app)71
8 unmodified lines
80 class Base(object):81 TEST_KEY = 'foo'8283 class Test(Base):84 SECRET_KEY = 'devkey'84 SECRET_KEY = 'config'8586 app = flask.Flask(__name__)87 app.config.from_object(Test)88 common_object_test(app)89
119 unmodified lines
modified:tests/test_signals.py+1 added-4 removed
155 unmodified lines
156 flask.appcontext_pushed.disconnect(record_push, app)157 flask.appcontext_popped.disconnect(record_pop, app)158159160def test_flash_signal():161 app = flask.Flask(__name__)162 app.config['SECRET_KEY'] = 'secret'163160def test_flash_signal(app):161 @app.route('/')162 def index():163 flask.flash('This is a flash message', category='notice')164 return flask.redirect('/other')
39 unmodified lines
modified:tests/test_templating.py-2 removed
50 unmodified lines
51 assert rv == 'Hello Special World 42'525354def test_standard_context(app, client):55 app.secret_key = 'development key'5655 @app.route('/')56 def index():57 flask.g.foo = 2358 flask.session['test'] = 'aha'
389 unmodified lines
modified:tests/test_testing.py-6 removed
105 unmodified lines
106 assert rv.data == b'http://xxx.example.com:1234/foo/'107108109def test_redirect_keep_session(app, client, app_ctx):110 app.secret_key = 'testing'111110 @app.route('/', methods=['GET', 'POST'])111 def index():112 if flask.request.method == 'POST':113 return flask.redirect('/getsession')
22 unmodified lines
136 assert rv.data == b'foo'137138139def test_session_transactions(app, client):142 app.secret_key = 'testing'143140 @app.route('/')141 def index():142 return text_type(flask.session['foo'])143
20 unmodified lines
164 assert 'Session backend did not open a session' in str(e.value)165166167def test_session_transactions_keep_context(app, client, req_ctx):172 app.secret_key = 'testing'173168 rv = client.get('/')169 req = flask.request._get_current_object()170 assert req is not None171 with client.session_transaction():
140 unmodified lines