Skip to content
Myr

Updated tutorial to the flask script

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 bacdd07 · Browse files · 4 files+36 added−49 removed
This commit

State

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

Diff stats

4 files+36 added−49 removed

  • other:+36 added−49 removed

4 files+36 added−49 removed

modified:docs/tutorial/dbinit.rst+21 added-25 removed
18 unmodified lines
19require that we provide the path to the database which can introduce20errors. It's a good idea to add a function that initializes the database21for you to the application.2223To do this we can create a function called `init_db` that initializes the24database. Let me show you the code first. Just add this function below25the `connect_db` function in `flaskr.py`::23To do this we can create a function and hook it into the ``flask`` command24that initializes the database. Let me show you the code first. Just add25this function below the `connect_db` function in `flaskr.py`::2627 @app.cli.command()27 def init_db():28 with app.app_context():29 db = get_db()30 with app.open_resource('schema.sql', mode='r') as f:31 db.cursor().executescript(f.read())32 db.commit()28 def initdb():29 """Initializes the database."""30 db = get_db()31 with app.open_resource('schema.sql', mode='r') as f:32 db.cursor().executescript(f.read())33 db.commit()34 print 'Initialized the database.'3534So what's happening here? Remember how we learned last chapter that the35application context is created every time a request comes in? Here we36don't have a request yet, so we need to create the application context by37hand. Without an application context the :data:`~flask.g` object does not38know yet to which application it becomes as there could be more than one!36The ``app.cli.command()`` decorator registers a new command with the37``flask`` script. When the command executes Flask will automatically38create a application context for us bound to the right application.39Within the function we can then access :attr:`flask.g` and other things as40we would expect. When the script ends, the application context tears down41and the database connection is released.4240The ``with app.app_context()`` statement establishes the application41context for us. In the body of the with statement the :data:`~flask.g`42object will be associated with ``app``. At the end of the with statement43the association is released and all teardown functions are executed. This44means that our database connection is disconnected after the commit.4543The :func:`~flask.Flask.open_resource` method of the application object44is a convenient helper function that will open a resource that the45application provides. This function opens a file from the resource46location (your `flaskr` folder) and allows you to read from it. We are
3 unmodified lines
50On that cursor there is a method to execute a complete script. Finally we51only have to commit the changes. SQLite 3 and other transactional52databases will not commit unless you explicitly tell it to.5357Now it is possible to create a database by starting up a Python shell and58importing and calling that function::54Now it is possible to create a database with the ``flask`` script::5560>>> from flaskr import init_db61>>> init_db()56 flask --app=flaskr initdb57 Initialized the database.5859.. admonition:: Troubleshooting6061 If you get an exception later that a table cannot be found check that66 you did call the `init_db` function and that your table names are62 you did execute the `initdb` command and that your table names are63 correct (singular vs. plural for example).6465Continue with :ref:`tutorial-views`
modified:docs/tutorial/setup.rst+6 added-12 removed
27 unmodified lines
2829 # Load default config and override config from an environment variable30 app.config.update(dict(31 DATABASE=os.path.join(app.root_path, 'flaskr.db'),32 DEBUG=True,32 SECRET_KEY='development key',33 USERNAME='admin',34 PASSWORD='default'35 ))
33 unmodified lines
69module. Flask will the initialize the variable from that module. Note70that in all cases only variable names that are uppercase are considered.7172The ``SECRET_KEY`` is needed to keep the client-side sessions secure.74Choose that key wisely and as hard to guess and complex as possible. The75debug flag enables or disables the interactive debugger. *Never leave76debug mode activated in a production system*, because it will allow users to77execute code on the server!73Choose that key wisely and as hard to guess and complex as possible.7475We will also add a method that allows for easily connecting to the76specified database. This can be used to open a connection on request and77also from the interactive Python shell or a script. This will come in
9 unmodified lines
87 rv = sqlite3.connect(app.config['DATABASE'])88 rv.row_factory = sqlite3.Row89 return rv9095Finally we just add a line to the bottom of the file that fires up the96server if we want to run that file as a standalone application::9798 if __name__ == '__main__':99 app.run()10091With that out of the way you should be able to start up the application92without problems. Do this with the following command::93104 python flaskr.py94 flask --app=flaskr --debug run9596The ``--debug`` flag enables or disables the interactive debugger. *Never97leave debug mode activated in a production system*, because it will allow98users to execute code on the server!99100You will see a message telling you that server has started along with101the address at which you can access it.102103When you head over to the server in your browser you will get an 404
10 unmodified lines
added:examples/flaskr/.gitignore+1 added
1flaskr.db
modified:examples/flaskr/flaskr.py+8 added-12 removed
35 unmodified lines
36 rv.row_factory = sqlite3.Row37 return rv383940@app.cli.command()40def init_db():41def initdb():42 """Creates the database tables."""42 with app.app_context():43 db = get_db()44 with app.open_resource('schema.sql', mode='r') as f:45 db.cursor().executescript(f.read())46 db.commit()43 db = get_db()44 with app.open_resource('schema.sql', mode='r') as f:45 db.cursor().executescript(f.read())46 db.commit()47 print('Initialized the database.')484950def get_db():51 """Opens a new database connection if there is none yet for the
24 unmodified lines
76 if not session.get('logged_in'):77 abort(401)78 db = get_db()79 db.execute('insert into entries (title, text) values (?, ?)',79 [request.form['title'], request.form['text']])80 [request.form['title'], request.form['text']])81 db.commit()82 flash('New entry was successfully posted')83 return redirect(url_for('show_entries'))84
17 unmodified lines
102def logout():103 session.pop('logged_in', None)104 flash('You were logged out')105 return redirect(url_for('show_entries'))105106107if __name__ == '__main__':108 init_db()109 app.run()