Ported examples over to new config. documented upgrading
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent 02b916d · Browse files · 17 files·+121 added−38 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
17 files+121 added−38 removed
- other:+121 added−38 removed
Provenance
- Commit
dfecc86- Tree
704167f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
02b916d
17 files changed+121 added−38 removed
modified:docs/patterns/appfactories.rst+2 added
1+.. _app-factories:2+3 Application Factories4 =====================5 6 If you are already using packages and modules for your application69 unmodified linesmodified:docs/patterns/jquery.rst+1 added-1 removed
75 unmodified lines76 In HTML the `script` tag is declared `CDATA` which means that entities77 will not be parsed. Everything until ``</script>`` is handled as script.78 This also means that there must never be any ``</`` between the script79 tags. ``|tojson`` is kindly enough to do the right thing here and80- escape slashes for you (``{{ "</script>"|tojson|safe }`` is rendered as80+ escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as81 ``"<\/script>"``).82 83 84 JSON View Functions83 unmodified linesmodified:docs/tutorial/setup.rst+19 added-4 removed
24 unmodified lines25 USERNAME = 'admin'26 PASSWORD = 'default'27 28 Next we can create our actual application and initialize it with the29-config::29+config from the same file::30 31 # create our little application :)32 app = Flask(__name__)33- app.secret_key = SECRET_KEY34- app.debug = DEBUG33+ app.config.from_object(__name__)34 35+:meth:`~flask.Config.from_object` will look at the given object (if it's a36+string it will import it) and then look for all uppercase variables37+defined there. In our case, the configuration we just wrote a few lines38+of code above. You can also move that into a separate file.39+40+It is also a good idea to be able to load a configuration from a41+configurable file. This is what :meth:`~flask.Config.from_envvar` can42+do::43+44+ app.config.from_envvar('FLASKR_SETTINGS', silent=True)45+46+That way someone can set an environment variable called47+:envvar:`FLASKR_SETTINGS` to specify a config file to be loaded which will48+then override the default values. The silent switch just tells Flask to49+not complain if no such environment key is set.50+51 The `secret_key` is needed to keep the client-side sessions secure.52 Choose that key wisely and as hard to guess and complex as possible. The53 debug flag enables or disables the interactive debugger. Never leave54 debug mode activated in a production system because it will allow users to5 unmodified lines60 61 ::62 63 def connect_db():49- return sqlite3.connect(DATABASE)64+ return sqlite3.connect(app.config['DATABASE'])65 66 Finally we just add a line to the bottom of the file that fires up the67 server if we run that file as standalone application::68 15 unmodified linesmodified:docs/tutorial/views.rst+2 added-2 removed
61 unmodified lines62 @app.route('/login', methods=['GET', 'POST'])63 def login():64 error = None65 if request.method == 'POST':66- if request.form['username'] != USERNAME:66+ if request.form['username'] != app.config['USERNAME']:67 error = 'Invalid username'68- elif request.form['password'] != PASSWORD:68+ elif request.form['password'] != app.config['PASSWORD']:69 error = 'Invalid password'70 else:71 session['logged_in'] = True72 flash('You were logged in')19 unmodified linesmodified:docs/_themesnot shown
Its text is not shown, modified.
modified:docs/becomingbig.rst-1 removed
25 unmodified lines26 27 Here are some suggestions for how Flask can be modified to better 28 accommodate large-scale applications:29 30-- implement dotted names for URL endpoints30 - get rid of the decorator function registering which causes a lot31 of troubles for applications that have circular dependencies. It32 also requires that the whole application is imported when the system33 initializes or certain URLs will not be available right away. A23 unmodified linesmodified:docs/config.rst+4 added
1+.. _config:2+3 Configuration Handling4 ======================5 6 .. versionadded:: 0.541 unmodified lines48 ----------------------------49 50 The following configuration values are used internally by Flask:51 52+.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|53+54 =============================== =========================================55 ``DEBUG`` enable/disable debug mode56 ``SECRET_KEY`` the secret key57 ``SESSION_COOKIE_NAME`` the name of the session cookie67 unmodified linesmodified:docs/contents.rst.inc+1 added
39 unmodified lines40 :maxdepth: 241 42 design43 license44+ upgrading45 changelogmodified:docs/foreword.rst-5 removed
82 unmodified lines83 widespread usage. Recent versions of Flask scale nicely within reasonable84 bounds and if you grow larger, you won't have any troubles adjusting Flask85 for your new application size.86 87-Flask serves two purposes: it's an example of how to create a minimal and88-opinionated framework on top of Werkzeug to show how this can be done, and89-to provide people with a simple tool to prototype larger applications or90-to implement small and medium sized applications.91-87 If you suddenly discover that your application grows larger than88 originally intended, head over to the :ref:`becomingbig` section to see89 some possible solutions for larger applications.90 1 unmodified linemodified:docs/testing.rst+9 added-5 removed
92 unmodified lines93 94 class FlaskrTestCase(unittest.TestCase):95 96 def setUp(self):97- self.db_fd, flaskr.DATABASE = tempfile.mkstemp()97+ self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()98 self.app = flaskr.app.test_client()99 flaskr.init_db()100 101 def tearDown(self):48 unmodified lines150 Now we can easily test if logging in and out works and that it fails with151 invalid credentials. Add this new test to the class::152 153 def test_login_logout(self):154- rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)154+ rv = self.login('admin', 'default')155 assert 'You were logged in' in rv.data156 rv = self.logout()157 assert 'You were logged out' in rv.data158- rv = self.login(flaskr.USERNAME + 'x', flaskr.PASSWORD)158+ rv = self.login('adminx', 'default')159 assert 'Invalid username' in rv.data160- rv = self.login(flaskr.USERNAME, flaskr.PASSWORD + 'x')160+ rv = self.login('admin', 'defaultx')161 assert 'Invalid password' in rv.data162 163 Test Adding Messages164 --------------------1 unmodified line166 Now we can also test that adding messages works. Add a new test method167 like this::168 169 def test_messages(self):170- self.login(flaskr.USERNAME, flaskr.PASSWORD)170+ self.login('admin', 'default')171 rv = self.app.post('/add', data=dict(172 title='<Hello>',173 text='<strong>HTML</strong> allowed here'174 ), follow_redirects=True)38 unmodified lines213 assert flask.request.path == '/'214 assert flask.request.args['name'] == 'Peter'215 216 All the other objects that are context bound can be used the same.217+218+If you want to test your application with different configurations and219+there does not seem to be a good way to do that, consider switching to220+application factories (see :ref:`app-factories`).added:docs/upgrading.rst+56 added
1+Upgrading to Newer Releases2+===========================3+4+Flask itself is changing like any software is changing over time. Most of5+the changes are the nice kind, the kind where you don't have th change6+anything in your code to profit from a new release.7+8+However every once in a while there are changes that do require some9+changes in your code or there are changes that make it possible for you to10+improve your own code quality by taking advantage of new features in11+Flask.12+13+This section of the documentation enumerates all the changes in Flask from14+release to release and how you can change your code to have a painless15+updating experience.16+17+Version 0.518+-----------19+20+Flask 0.5 introduces configuration support and logging as well as21+categories for flashing messages. All these are features that are 100%22+backwards compatible but you might want to take advantage of them.23+24+Configuration Support25+`````````````````````26+27+The configuration support makes it easier to write any kind of application28+that requires some sort of configuration. (Which most likely is the case29+for any application out there).30+31+If you previously had code like this::32+33+ app.debug = DEBUG34+ app.secret_key = SECRET_KEY35+36+You no longer have to do that, instead you can just load a configuration37+into the config object. How this works is outlined in :ref:`config`.38+39+Logging Integration40+```````````````````41+42+Flask now configures a logger for you with some basic and useful defaults.43+If you run your application in production and want to profit from44+automatic error logging, you might be interested in attaching a proper log45+handler. Also you can start logging warnings and errors into the logger46+when appropriately. For more information on that, read47+:ref:`application-errors`.48+49+Categories for Flash Messages50+`````````````````````````````51+52+Flash messages can now have categories attached. This makes it possible53+to render errors, warnings or regular messages differently for example.54+This is an opt-in feature because it requires some rethinking in the code.55+56+Read all about that in the :ref:`message-flashing-pattern` pattern.modified:examples/flaskr/flaskr_tests.py+10 added-6 removed
16 unmodified lines17 class FlaskrTestCase(unittest.TestCase):18 19 def setUp(self):20 """Before each test, set up a blank database"""21- self.db_fd, flaskr.DATABASE = tempfile.mkstemp()21+ self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()22 self.app = flaskr.app.test_client()23 flaskr.init_db()24 25 def tearDown(self):26 """Get rid of the database again after each test."""27 os.close(self.db_fd)28- os.unlink(flaskr.DATABASE)28+ os.unlink(flaskr.app.config['DATABASE'])29 30 def login(self, username, password):31 return self.app.post('/login', data=dict(32 username=username,11 unmodified lines44 assert 'No entries here so far' in rv.data45 46 def test_login_logout(self):47 """Make sure login and logout works"""48- rv = self.login(flaskr.USERNAME, flaskr.PASSWORD)48+ rv = self.login(flaskr.app.config['USERNAME'],49+ flaskr.app.config['PASSWORD'])50 assert 'You were logged in' in rv.data51 rv = self.logout()52 assert 'You were logged out' in rv.data52- rv = self.login(flaskr.USERNAME + 'x', flaskr.PASSWORD)53+ rv = self.login(flaskr.app.config['USERNAME'] + 'x',54+ flaskr.app.config['PASSWORD'])55 assert 'Invalid username' in rv.data54- rv = self.login(flaskr.USERNAME, flaskr.PASSWORD + 'x')56+ rv = self.login(flaskr.app.config['USERNAME'],57+ flaskr.app.config['PASSWORD'] + 'x')58 assert 'Invalid password' in rv.data59 60 def test_messages(self):61 """Test that messages work"""59- self.login(flaskr.USERNAME, flaskr.PASSWORD)62+ self.login(flaskr.app.config['USERNAME'],63+ flaskr.app.config['PASSWORD'])64 rv = self.app.post('/add', data=dict(65 title='<Hello>',66 text='<strong>HTML</strong> allowed here'67 ), follow_redirects=True)7 unmodified linesmodified:examples/flaskr/flaskr.py+5 added-5 removed
22 unmodified lines23 PASSWORD = 'default'24 25 # create our little application :)26 app = Flask(__name__)27-app.secret_key = SECRET_KEY28-app.debug = DEBUG27+app.config.from_object(__name__)28+app.config.from_envvar('FLASKR_SETTINGS', silent=True)29 30 31 def connect_db():32 """Returns a new connection to the database."""33- return sqlite3.connect(DATABASE)33+ return sqlite3.connect(app.config['DATABASE'])34 35 36 def init_db():37 """Creates the database tables."""37 unmodified lines75 @app.route('/login', methods=['GET', 'POST'])76 def login():77 error = None78 if request.method == 'POST':79- if request.form['username'] != USERNAME:79+ if request.form['username'] != app.config['USERNAME']:80 error = 'Invalid username'81- elif request.form['password'] != PASSWORD:81+ elif request.form['password'] != app.config['PASSWORD']:82 error = 'Invalid password'83 else:84 session['logged_in'] = True85 flash('You were logged in')13 unmodified linesmodified:examples/flaskr/README+3 added-1 removed
8 unmodified lines9 A sqlite powered thumble blog application10 11 ~ How do I use it?12 13- 1. edit the configuration in the flaskr.py file13+ 1. edit the configuration in the flaskr.py file or14+ export an FLASKR_SETTINGS environment variable15+ pointing to a configuration file.16 17 2. fire up a python shell and run this:18 19 >>> from flaskr import init_db; init_db()9 unmodified linesmodified:examples/minitwit/minitwit_tests.py+2 added-2 removed
16 unmodified lines17 class MiniTwitTestCase(unittest.TestCase):18 19 def setUp(self):20 """Before each test, set up a blank database"""21- self.db_fd, minitwit.DATABASE = tempfile.mkstemp()21+ self.db_fd, minitwit.app.config['DATABASE'] = tempfile.mkstemp()22 self.app = minitwit.app.test_client()23 minitwit.init_db()24 25 def tearDown(self):26 """Get rid of the database again after each test."""27 os.close(self.db_fd)28- os.unlink(minitwit.DATABASE)28+ os.unlink(minitwit.app.config['DATABASE'])29 30 # helper functions31 32 def register(self, username, password, password2=None, email=None):117 unmodified linesmodified:examples/minitwit/minitwit.py+4 added-5 removed
25 unmodified lines26 SECRET_KEY = 'development key'27 28 # create our little application :)29 app = Flask(__name__)30+app.config.from_object(__name__)31+app.config.from_envvar('MINITWIT_SETTINGS', silent=True)32 33 34 def connect_db():35 """Returns a new connection to the database."""34- return sqlite3.connect(DATABASE)36+ return sqlite3.connect(app.config['DATABASE'])37 38 39 def init_db():40 """Creates the database tables."""197 unmodified lines238 session.pop('user_id', None)239 return redirect(url_for('public_timeline'))240 241 240-# add some filters to jinja and set the secret key and debug mode241-# from the configuration.242+# add some filters to jinja243 app.jinja_env.filters['datetimeformat'] = format_datetime244 app.jinja_env.filters['gravatar'] = gravatar_url244-app.secret_key = SECRET_KEY245-app.debug = DEBUG245 246 247 if __name__ == '__main__':248 app.run()modified:examples/minitwit/README+3 added-1 removed
8 unmodified lines9 A SQLite and Flask powered twitter clone10 11 ~ How do I use it?12 13- 1. edit the configuration in the minitwit.py file13+ 1. edit the configuration in the minitwit.py file or14+ export an MINITWIT_SETTINGS environment variable15+ pointing to a configuration file.16 17 2. fire up a python shell and run this:18 19 >>> from minitwit import init_db; init_db()9 unmodified lines