Minor edits to tutorial for clarity. (#2330)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dave Morse · committed by David Lord · parent 471c7f3 · Browse files · 8 files·+103 added−85 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+103 added−85 removed
- other:+103 added−85 removed
Provenance
- Commit
50c6df7- Tree
1ee4eeb- Author
Dave Morse <openmorse@users.noreply.github.com>- Committer
David Lord <davidism@gmail.com>- Parent
471c7f3
8 files changed+103 added−85 removed
modified:docs/tutorial/dbcon.rst+3 added
1 unmodified line2 3 Step 4: Database Connections4 ----------------------------5 6+Let's continue building our code in the ``flaskr.py`` file.7+(Scroll to the end of the page for more about project layout.)8+9 You currently have a function for establishing a database connection with10 `connect_db`, but by itself, it is not particularly useful. Creating and11 closing database connections all the time is very inefficient, so you will12 need to keep it around for longer. Because database connections66 unmodified linesmodified:docs/tutorial/dbinit.rst+19 added-12 removed
7 unmodified lines8 systems need a schema that tells them how to store that information.9 Before starting the server for the first time, it's important to create10 that schema.11 12-Such a schema can be created by piping the ``schema.sql`` file into the13-`sqlite3` command as follows::12+Such a schema could be created by piping the ``schema.sql`` file into the13+``sqlite3`` command as follows::14 15 sqlite3 /tmp/flaskr.db < schema.sql16 17-The downside of this is that it requires the ``sqlite3`` command to be18-installed, which is not necessarily the case on every system. This also19-requires that you 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.17+However, the downside of this is that it requires the ``sqlite3`` command18+to be installed, which is not necessarily the case on every system. This19+also requires that you provide the path to the database, which can introduce20+errors.21 23-To do this, you can create a function and hook it into a :command:`flask`24-command that initializes the database. For now just take a look at the25-code segment below. A good place to add this function, and command, is26-just below the `connect_db` function in :file:`flaskr.py`::22+Instead of the ``sqlite3`` command above, it's a good idea to add a function23+to our application that initializes the database for you. To do this, you24+can create a function and hook it into a :command:`flask` command that25+initializes the database.26 27+Take a look at the code segment below. A good place to add this function,28+and command, is just below the ``connect_db`` function in :file:`flaskr.py`::29+30 def init_db():31 db = get_db()32+33 with app.open_resource('schema.sql', mode='r') as f:34 db.cursor().executescript(f.read())35+36 db.commit()37 38+39 @app.cli.command('initdb')40 def initdb_command():41 """Initializes the database."""42+43 init_db()44 print('Initialized the database.')45 46 The ``app.cli.command()`` decorator registers a new command with the17 unmodified lines64 On that cursor, there is a method to execute a complete script. Finally, you65 only have to commit the changes. SQLite3 and other transactional66 databases will not commit unless you explicitly tell it to.67 68+Now, in a terminal, from the application root directory :file:`flaskr/` it is62-Now, it is possible to create a database with the :command:`flask` script::69+possible to create a database with the :command:`flask` script::70 71 flask initdb72 Initialized the database.73 7 unmodified linesmodified:docs/tutorial/folders.rst+9 added-5 removed
1 unmodified line2 3 Step 0: Creating The Folders4 ============================5 6-Before getting started, you will need to create the folders needed for this7-application::6+It is recommended to install your Flask application within a virtualenv. Please7+read the :ref:`installation` section to set up your environment.8 9+Now that you have installed Flask, you will need to create the folders required10+for this tutorial. Your directory structure will look like this::11+12 /flaskr13 /flaskr14 /static15 /templates16 17 The application will be installed and run as Python package. This is the18 recommended way to install and run Flask applications. You will see exactly16-how to run ``flaskr`` later on in this tutorial. For now go ahead and create17-the applications directory structure. In the next few steps you will be18-creating the database schema as well as the main module.19+how to run ``flaskr`` later on in this tutorial.20 21+For now go ahead and create the applications directory structure. In the next22+few steps you will be creating the database schema as well as the main module.23+24 As a quick side note, the files inside of the :file:`static` folder are25 available to users of the application via HTTP. This is the place where CSS and26 JavaScript files go. Inside the :file:`templates` folder, Flask will look for27 `Jinja2`_ templates. You will see examples of this later on.4 unmodified linesmodified:docs/tutorial/index.rst+9 added-9 removed
1 unmodified line2 3 Tutorial4 ========5 6-You want to develop an application with Python and Flask? Here you have7-the chance to learn by example. In this tutorial, we will create a simple8-microblogging application. It only supports one user that can create9-text-only entries and there are no feeds or comments, but it still10-features everything you need to get started. We will use Flask and SQLite11-as a database (which comes out of the box with Python) so there is nothing12-else you need.6+Learn by example to develop an application with Python and Flask.7 8+In this tutorial, we will create a simple blogging application. It only9+supports one user, only allows text entries, and has no feeds or comments.10+11+While very simple, this example still features everything you need to get12+started. In addition to Flask, we will use SQLite for the database, which is13+built-in to Python, so there is nothing else you need.14+15 If you want the full source code in advance or for comparison, check out16 the `example source`_.17 17-.. _example source:18- https://github.com/pallets/flask/tree/master/examples/flaskr/18+.. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/19 20 .. toctree::21 :maxdepth: 222 11 unmodified linesmodified:docs/tutorial/packaging.rst+24 added-26 removed
7 unmodified lines8 tutorial you will see exactly how to extend the ``flask`` command line9 interface (CLI).10 11 A useful pattern to manage a Flask application is to install your app12-following the `Python Packaging Guide`_. Presently this involves 13-creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the 14-projects root directory. You also need to add an :file:`__init__.py` 15-file to make the :file:`flaskr/flaskr` directory a package. After these 12+following the `Python Packaging Guide`_. Presently this involves13+creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the14+projects root directory. You also need to add an :file:`__init__.py`15+file to make the :file:`flaskr/flaskr` directory a package. After these16 changes, your code structure should be::17 18 /flaskr19 /flaskr4 unmodified lines24 schema.sql25 setup.py26 MANIFEST.in27 28-The content of the ``setup.py`` file for ``flaskr`` is:28+Create the ``setup.py`` file for ``flaskr`` with the following content::29 30-.. sourcecode:: python31-30 from setuptools import setup31 32 setup(33 name='flaskr',6 unmodified lines40 41 When using setuptools, it is also necessary to specify any special files42 that should be included in your package (in the :file:`MANIFEST.in`).43 In this case, the static and templates directories need to be included,46-as well as the schema. Create the :file:`MANIFEST.in` and add the47-following lines::44+as well as the schema.45 46+Create the :file:`MANIFEST.in` and add the following lines::47+48 graft flaskr/templates49 graft flaskr/static50 include flaskr/schema.sql51 53-To simplify locating the application, add the following import statement 54-into this file, :file:`flaskr/__init__.py`:52+Next, to simplify locating the application, create the file,53+:file:`flaskr/__init__.py` containing only the following import statement::54 56-.. sourcecode:: python57-55 from .flaskr import app56 60-This import statement brings the application instance into the top-level 61-of the application package. When it is time to run the application, the 62-Flask development server needs the location of the app instance. This 63-import statement simplifies the location process. Without it the export 64-statement a few steps below would need to be 57+This import statement brings the application instance into the top-level58+of the application package. When it is time to run the application, the59+Flask development server needs the location of the app instance. This60+import statement simplifies the location process. Without the above61+import statement, the export statement a few steps below would need to be62 ``export FLASK_APP=flaskr.flaskr``.63 64 At this point you should be able to install the application. As usual, it65 is recommended to install your Flask application within a `virtualenv`_.69-With that said, go ahead and install the application with::66+With that said, from the ``flaskr/`` directory, go ahead and install the67+application with::68 69 pip install --editable .70 73-The above installation command assumes that it is run within the projects 74-root directory, `flaskr/`. The `editable` flag allows editing 75-source code without having to reinstall the Flask app each time you make 76-changes. The flaskr app is now installed in your virtualenv (see output 71+The above installation command assumes that it is run within the projects72+root directory, ``flaskr/``. The ``editable`` flag allows editing73+source code without having to reinstall the Flask app each time you make74+changes. The flaskr app is now installed in your virtualenv (see output75 of ``pip freeze``).76 77 With that out of the way, you should be able to start up the application.80-Do this with the following commands::78+Do this on Mac or Linux with the following commands in ``flaskr/``::79 80 export FLASK_APP=flaskr81 export FLASK_DEBUG=true82 flask run83 86-(In case you are on Windows you need to use `set` instead of `export`).84+(In case you are on Windows you need to use ``set`` instead of ``export``).85 The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.86 *Never leave debug mode activated in a production system*, because it will87 allow users to execute code on the server!88 89 You will see a message telling you that server has started along with92-the address at which you can access it.90+the address at which you can access it in a browser.91 92 When you head over to the server in your browser, you will get a 404 error93 because we don't have any views yet. That will be addressed a little later,94 but first, you should get the database working.12 unmodified linesmodified:docs/tutorial/setup.rst+35 added-31 removed
1 unmodified line2 3 Step 2: Application Setup Code4 ==============================5 6-Now that the schema is in place, you can create the application module,7-:file:`flaskr.py`. This file should be placed inside of the8-:file:`flaskr/flaskr` folder. The first several lines of code in the9-application module are the needed import statements. After that there will be a10-few lines of configuration code. For small applications like ``flaskr``, it is11-possible to drop the configuration directly into the module. However, a cleaner12-solution is to create a separate ``.ini`` or ``.py`` file, load that, and13-import the values from there.6+Next, we will create the application module, :file:`flaskr.py`. Just like the7+:file:`schema.sql` file you created in the previous step, this file should be8+placed inside of the :file:`flaskr/flaskr` folder.9 10+For this tutorial, all the Python code we use will be put into this file11+(except for one line in ``__init__.py``, and any testing or optional files you12+decide to create).13+14+The first several lines of code in the application module are the needed import15+statements. After that there will be a few lines of configuration code.16+17+For small applications like ``flaskr``, it is possible to drop the configuration18+directly into the module. However, a cleaner solution is to create a separate19+``.py`` file, load that, and import the values from there.20+21 Here are the import statements (in :file:`flaskr.py`)::22 17- # all the imports23 import os24 import sqlite320- from flask import Flask, request, session, g, redirect, url_for, abort, \21- render_template, flash25 26+ from flask import (Flask, request, session, g, redirect, url_for, abort,27+ render_template, flash)28+29 The next couple lines will create the actual application instance and24-initialize it with the config from the same file in :file:`flaskr.py`:30+initialize it with the config from the same file in :file:`flaskr.py`::31 26-.. sourcecode:: python27-32 app = Flask(__name__) # create the application instance :)33 app.config.from_object(__name__) # load config from this file , flaskr.py34 35 # Load default config and override config from an environment variable4 unmodified lines40 PASSWORD='default'41 ))42 app.config.from_envvar('FLASKR_SETTINGS', silent=True)43 40-The :class:`~flask.Config` object works similarly to a dictionary, so it can be41-updated with new values.44+In the above code, the :class:`~flask.Config` object works similarly to a45+dictionary, so it can be updated with new values.46 47 .. admonition:: Database Path48 49 Operating systems know the concept of a current working directory for11 unmodified lines61 62 Usually, it is a good idea to load a separate, environment-specific63 configuration file. Flask allows you to import multiple configurations and it64 will use the setting defined in the last import. This enables robust61-configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.65+configuration setups. :meth:`~flask.Config.from_envvar` can help achieve66+this. ::67 63-.. sourcecode:: python64-68 app.config.from_envvar('FLASKR_SETTINGS', silent=True)69 67-Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to68-a config file to be loaded. The silent switch just tells Flask to not complain69-if no such environment key is set.70+If you want to do this (not required for this tutorial) simply define the71+environment variable :envvar:`FLASKR_SETTINGS` that points to a config file72+to be loaded. The silent switch just tells Flask to not complain if no such73+environment key is set.74 75 In addition to that, you can use the :meth:`~flask.Config.from_object`76 method on the config object and provide it with an import name of a77 module. Flask will then initialize the variable from that module. Note1 unmodified line79 80 The ``SECRET_KEY`` is needed to keep the client-side sessions secure.81 Choose that key wisely and as hard to guess and complex as possible.82 79-Lastly, you will add a method that allows for easy connections to the80-specified database. This can be used to open a connection on request and81-also from the interactive Python shell or a script. This will come in82-handy later. You can create a simple database connection through SQLite and83-then tell it to use the :class:`sqlite3.Row` object to represent rows.84-This allows the rows to be treated as if they were dictionaries instead of85-tuples.83+Lastly, add a method that allows for easy connections to the specified84+database. ::85 87-.. sourcecode:: python88-86 def connect_db():87 """Connects to the specific database."""88+89 rv = sqlite3.connect(app.config['DATABASE'])90 rv.row_factory = sqlite3.Row91 return rv92 93+This can be used to open a connection on request and also from the94+interactive Python shell or a script. This will come in handy later.95+You can create a simple database connection through SQLite and then tell96+it to use the :class:`sqlite3.Row` object to represent rows. This allows97+the rows to be treated as if they were dictionaries instead of tuples.98+99 In the next section you will see how to run the application.100 101 Continue with :ref:`tutorial-packaging`.modified:docs/tutorial/templates.rst+2 added-1 removed
13 unmodified lines14 15 We are also using template inheritance which makes it possible to reuse16 the layout of the website in all pages.17 18-Put the following templates into the :file:`templates` folder:18+Create the follwing three HTML files and place them in the19+:file:`templates` folder:20 21 .. _Jinja2: http://jinja.pocoo.org/docs/templates22 23 layout.html90 unmodified linesmodified:docs/tutorial/views.rst+2 added-1 removed
2 unmodified lines3 Step 6: The View Functions4 ==========================5 6 Now that the database connections are working, you can start writing the7-view functions. You will need four of them:7+view functions. You will need four of them; Show Entries, Add New Entry,8+Login and Logout. Add the following code snipets to :file:`flaskr.py`.9 10 Show Entries11 ------------12 106 unmodified lines