Skip to content
Myr

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

17 files+121 added−38 removed

modified:docs/patterns/appfactories.rst+2 added
1.. _app-factories:23Application Factories4=====================56If you are already using packages and modules for your application
69 unmodified lines
modified:docs/patterns/jquery.rst+1 added-1 removed
75 unmodified lines
76 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>"``).828384JSON View Functions
83 unmodified lines
modified:docs/tutorial/setup.rst+19 added-4 removed
24 unmodified lines
25 USERNAME = 'admin'26 PASSWORD = 'default'2728Next we can create our actual application and initialize it with the29config::29config from the same file::3031 # create our little application :)32 app = Flask(__name__)33 app.secret_key = SECRET_KEY34 app.debug = DEBUG33 app.config.from_object(__name__)3435:meth:`~flask.Config.from_object` will look at the given object (if it's a36string it will import it) and then look for all uppercase variables37defined there. In our case, the configuration we just wrote a few lines38of code above. You can also move that into a separate file.3940It is also a good idea to be able to load a configuration from a41configurable file. This is what :meth:`~flask.Config.from_envvar` can42do::4344 app.config.from_envvar('FLASKR_SETTINGS', silent=True)4546That way someone can set an environment variable called47:envvar:`FLASKR_SETTINGS` to specify a config file to be loaded which will48then override the default values. The silent switch just tells Flask to49not complain if no such environment key is set.5051The `secret_key` is needed to keep the client-side sessions secure.52Choose that key wisely and as hard to guess and complex as possible. The53debug flag enables or disables the interactive debugger. Never leave54debug mode activated in a production system because it will allow users to
5 unmodified lines
6061::6263 def connect_db():49 return sqlite3.connect(DATABASE)64 return sqlite3.connect(app.config['DATABASE'])6566Finally we just add a line to the bottom of the file that fires up the67server if we run that file as standalone application::68
15 unmodified lines
modified:docs/tutorial/views.rst+2 added-2 removed
61 unmodified lines
62 @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 lines
modified:docs/_themesnot shown

Its text is not shown, modified.

modified:docs/becomingbig.rst-1 removed
25 unmodified lines
2627Here are some suggestions for how Flask can be modified to better 28accommodate large-scale applications:2930- 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. A
23 unmodified lines
modified:docs/config.rst+4 added
1.. _config:23Configuration Handling4======================56.. versionadded:: 0.5
41 unmodified lines
48----------------------------4950The following configuration values are used internally by Flask:5152.. tabularcolumns:: |p{6.5cm}|p{8.5cm}|5354=============================== =========================================55``DEBUG`` enable/disable debug mode56``SECRET_KEY`` the secret key57``SESSION_COOKIE_NAME`` the name of the session cookie
67 unmodified lines
modified:docs/contents.rst.inc+1 added
39 unmodified lines
40 :maxdepth: 24142 design43 license44 upgrading45 changelog
modified:docs/foreword.rst-5 removed
82 unmodified lines
83widespread usage. Recent versions of Flask scale nicely within reasonable84bounds and if you grow larger, you won't have any troubles adjusting Flask85for your new application size.8687Flask serves two purposes: it's an example of how to create a minimal and88opinionated framework on top of Werkzeug to show how this can be done, and89to provide people with a simple tool to prototype larger applications or90to implement small and medium sized applications.9187If you suddenly discover that your application grows larger than88originally intended, head over to the :ref:`becomingbig` section to see89some possible solutions for larger applications.90
1 unmodified line
modified:docs/testing.rst+9 added-5 removed
92 unmodified lines
9394 class FlaskrTestCase(unittest.TestCase):9596 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()100101 def tearDown(self):
48 unmodified lines
150Now we can easily test if logging in and out works and that it fails with151invalid credentials. Add this new test to the class::152153 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.data162163Test Adding Messages164--------------------
1 unmodified line
166Now we can also test that adding messages works. Add a new test method167like this::168169 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 lines
213 assert flask.request.path == '/'214 assert flask.request.args['name'] == 'Peter'215216All the other objects that are context bound can be used the same.217218If you want to test your application with different configurations and219there does not seem to be a good way to do that, consider switching to220application factories (see :ref:`app-factories`).
added:docs/upgrading.rst+56 added
1Upgrading to Newer Releases2===========================34Flask itself is changing like any software is changing over time. Most of5the changes are the nice kind, the kind where you don't have th change6anything in your code to profit from a new release.78However every once in a while there are changes that do require some9changes in your code or there are changes that make it possible for you to10improve your own code quality by taking advantage of new features in11Flask.1213This section of the documentation enumerates all the changes in Flask from14release to release and how you can change your code to have a painless15updating experience.1617Version 0.518-----------1920Flask 0.5 introduces configuration support and logging as well as21categories for flashing messages. All these are features that are 100%22backwards compatible but you might want to take advantage of them.2324Configuration Support25`````````````````````2627The configuration support makes it easier to write any kind of application28that requires some sort of configuration. (Which most likely is the case29for any application out there).3031If you previously had code like this::3233 app.debug = DEBUG34 app.secret_key = SECRET_KEY3536You no longer have to do that, instead you can just load a configuration37into the config object. How this works is outlined in :ref:`config`.3839Logging Integration40```````````````````4142Flask now configures a logger for you with some basic and useful defaults.43If you run your application in production and want to profit from44automatic error logging, you might be interested in attaching a proper log45handler. Also you can start logging warnings and errors into the logger46when appropriately. For more information on that, read47:ref:`application-errors`.4849Categories for Flash Messages50`````````````````````````````5152Flash messages can now have categories attached. This makes it possible53to render errors, warnings or regular messages differently for example.54This is an opt-in feature because it requires some rethinking in the code.5556Read all about that in the :ref:`message-flashing-pattern` pattern.
modified:examples/flaskr/flaskr_tests.py+10 added-6 removed
16 unmodified lines
17class FlaskrTestCase(unittest.TestCase):1819 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()2425 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'])2930 def login(self, username, password):31 return self.app.post('/login', data=dict(32 username=username,
11 unmodified lines
44 assert 'No entries here so far' in rv.data4546 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.data5960 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 lines
modified:examples/flaskr/flaskr.py+5 added-5 removed
22 unmodified lines
23PASSWORD = 'default'2425# create our little application :)26app = Flask(__name__)27app.secret_key = SECRET_KEY28app.debug = DEBUG27app.config.from_object(__name__)28app.config.from_envvar('FLASKR_SETTINGS', silent=True)293031def connect_db():32 """Returns a new connection to the database."""33 return sqlite3.connect(DATABASE)33 return sqlite3.connect(app.config['DATABASE'])343536def init_db():37 """Creates the database tables."""
37 unmodified lines
75@app.route('/login', methods=['GET', 'POST'])76def 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 lines
modified:examples/flaskr/README+3 added-1 removed
8 unmodified lines
9 A sqlite powered thumble blog application1011 ~ How do I use it?1213 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.1617 2. fire up a python shell and run this:1819 >>> from flaskr import init_db; init_db()
9 unmodified lines
modified:examples/minitwit/minitwit_tests.py+2 added-2 removed
16 unmodified lines
17class MiniTwitTestCase(unittest.TestCase):1819 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()2425 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'])2930 # helper functions3132 def register(self, username, password, password2=None, email=None):
117 unmodified lines
modified:examples/minitwit/minitwit.py+4 added-5 removed
25 unmodified lines
26SECRET_KEY = 'development key'2728# create our little application :)29app = Flask(__name__)30app.config.from_object(__name__)31app.config.from_envvar('MINITWIT_SETTINGS', silent=True)323334def connect_db():35 """Returns a new connection to the database."""34 return sqlite3.connect(DATABASE)36 return sqlite3.connect(app.config['DATABASE'])373839def init_db():40 """Creates the database tables."""
197 unmodified lines
238 session.pop('user_id', None)239 return redirect(url_for('public_timeline'))240241240# add some filters to jinja and set the secret key and debug mode241# from the configuration.242# add some filters to jinja243app.jinja_env.filters['datetimeformat'] = format_datetime244app.jinja_env.filters['gravatar'] = gravatar_url244app.secret_key = SECRET_KEY245app.debug = DEBUG245246247if __name__ == '__main__':248 app.run()
modified:examples/minitwit/README+3 added-1 removed
8 unmodified lines
9 A SQLite and Flask powered twitter clone1011 ~ How do I use it?1213 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.1617 2. fire up a python shell and run this:1819 >>> from minitwit import init_db; init_db()
9 unmodified lines