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
Provenance
- Commit
a3a5075- Tree
e4fbf64- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
bacdd07
4 files changed+36 added−49 removed
modified:docs/tutorial/dbinit.rst+21 added-25 removed
18 unmodified lines19 require that we provide the path to the database which can introduce20 errors. It's a good idea to add a function that initializes the database21 for you to the application.22 23-To do this we can create a function called `init_db` that initializes the24-database. Let me show you the code first. Just add this function below25-the `connect_db` function in `flaskr.py`::23+To do this we can create a function and hook it into the ``flask`` command24+that initializes the database. Let me show you the code first. Just add25+this function below the `connect_db` function in `flaskr.py`::26 27+ @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.'35 34-So what's happening here? Remember how we learned last chapter that the35-application context is created every time a request comes in? Here we36-don't have a request yet, so we need to create the application context by37-hand. Without an application context the :data:`~flask.g` object does not38-know yet to which application it becomes as there could be more than one!36+The ``app.cli.command()`` decorator registers a new command with the37+``flask`` script. When the command executes Flask will automatically38+create a application context for us bound to the right application.39+Within the function we can then access :attr:`flask.g` and other things as40+we would expect. When the script ends, the application context tears down41+and the database connection is released.42 40-The ``with app.app_context()`` statement establishes the application41-context for us. In the body of the with statement the :data:`~flask.g`42-object will be associated with ``app``. At the end of the with statement43-the association is released and all teardown functions are executed. This44-means that our database connection is disconnected after the commit.45-43 The :func:`~flask.Flask.open_resource` method of the application object44 is a convenient helper function that will open a resource that the45 application provides. This function opens a file from the resource46 location (your `flaskr` folder) and allows you to read from it. We are3 unmodified lines50 On that cursor there is a method to execute a complete script. Finally we51 only have to commit the changes. SQLite 3 and other transactional52 databases will not commit unless you explicitly tell it to.53 57-Now it is possible to create a database by starting up a Python shell and58-importing and calling that function::54+Now it is possible to create a database with the ``flask`` script::55 60->>> from flaskr import init_db61->>> init_db()56+ flask --app=flaskr initdb57+ Initialized the database.58 59 .. admonition:: Troubleshooting60 61 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).64 65 Continue with :ref:`tutorial-views`modified:docs/tutorial/setup.rst+6 added-12 removed
27 unmodified lines28 29 # 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 lines69 module. Flask will the initialize the variable from that module. Note70 that in all cases only variable names that are uppercase are considered.71 72 The ``SECRET_KEY`` is needed to keep the client-side sessions secure.74-Choose that key wisely and as hard to guess and complex as possible. The75-debug flag enables or disables the interactive debugger. *Never leave76-debug mode activated in a production system*, because it will allow users to77-execute code on the server!73+Choose that key wisely and as hard to guess and complex as possible.74 75 We will also add a method that allows for easily connecting to the76 specified database. This can be used to open a connection on request and77 also from the interactive Python shell or a script. This will come in9 unmodified lines87 rv = sqlite3.connect(app.config['DATABASE'])88 rv.row_factory = sqlite3.Row89 return rv90 95-Finally we just add a line to the bottom of the file that fires up the96-server if we want to run that file as a standalone application::97-98- if __name__ == '__main__':99- app.run()100-91 With that out of the way you should be able to start up the application92 without problems. Do this with the following command::93 104- python flaskr.py94+ flask --app=flaskr --debug run95 96+The ``--debug`` flag enables or disables the interactive debugger. *Never97+leave debug mode activated in a production system*, because it will allow98+users to execute code on the server!99+100 You will see a message telling you that server has started along with101 the address at which you can access it.102 103 When you head over to the server in your browser you will get an 40410 unmodified linesadded:examples/flaskr/.gitignore+1 added
1+flaskr.dbmodified:examples/flaskr/flaskr.py+8 added-12 removed
35 unmodified lines36 rv.row_factory = sqlite3.Row37 return rv38 39 40+@app.cli.command()40-def init_db():41+def 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.')48 49 50 def get_db():51 """Opens a new database connection if there is none yet for the24 unmodified lines76 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 lines102 def logout():103 session.pop('logged_in', None)104 flash('You were logged out')105 return redirect(url_for('show_entries'))105-106-107-if __name__ == '__main__':108- init_db()109- app.run()