Skip to content
Myr

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

8 files+103 added−85 removed

modified:docs/tutorial/dbcon.rst+3 added
1 unmodified line
23Step 4: Database Connections4----------------------------56Let's continue building our code in the ``flaskr.py`` file.7(Scroll to the end of the page for more about project layout.)89You currently have a function for establishing a database connection with10`connect_db`, but by itself, it is not particularly useful. Creating and11closing database connections all the time is very inefficient, so you will12need to keep it around for longer. Because database connections
66 unmodified lines
modified:docs/tutorial/dbinit.rst+19 added-12 removed
7 unmodified lines
8systems need a schema that tells them how to store that information.9Before starting the server for the first time, it's important to create10that schema.1112Such a schema can be created by piping the ``schema.sql`` file into the13`sqlite3` command as follows::12Such a schema could be created by piping the ``schema.sql`` file into the13``sqlite3`` command as follows::1415 sqlite3 /tmp/flaskr.db < schema.sql1617The downside of this is that it requires the ``sqlite3`` command to be18installed, which is not necessarily the case on every system. This also19requires that you 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.17However, the downside of this is that it requires the ``sqlite3`` command18to be installed, which is not necessarily the case on every system. This19also requires that you provide the path to the database, which can introduce20errors.2123To do this, you can create a function and hook it into a :command:`flask`24command that initializes the database. For now just take a look at the25code segment below. A good place to add this function, and command, is26just below the `connect_db` function in :file:`flaskr.py`::22Instead of the ``sqlite3`` command above, it's a good idea to add a function23to our application that initializes the database for you. To do this, you24can create a function and hook it into a :command:`flask` command that25initializes the database.2627Take a look at the code segment below. A good place to add this function,28and command, is just below the ``connect_db`` function in :file:`flaskr.py`::2930 def init_db():31 db = get_db()3233 with app.open_resource('schema.sql', mode='r') as f:34 db.cursor().executescript(f.read())3536 db.commit()373839 @app.cli.command('initdb')40 def initdb_command():41 """Initializes the database."""4243 init_db()44 print('Initialized the database.')4546The ``app.cli.command()`` decorator registers a new command with the
17 unmodified lines
64On that cursor, there is a method to execute a complete script. Finally, you65only have to commit the changes. SQLite3 and other transactional66databases will not commit unless you explicitly tell it to.6768Now, in a terminal, from the application root directory :file:`flaskr/` it is62Now, it is possible to create a database with the :command:`flask` script::69possible to create a database with the :command:`flask` script::7071 flask initdb72 Initialized the database.73
7 unmodified lines
modified:docs/tutorial/folders.rst+9 added-5 removed
1 unmodified line
23Step 0: Creating The Folders4============================56Before getting started, you will need to create the folders needed for this7application::6It is recommended to install your Flask application within a virtualenv. Please7read the :ref:`installation` section to set up your environment.89Now that you have installed Flask, you will need to create the folders required10for this tutorial. Your directory structure will look like this::1112 /flaskr13 /flaskr14 /static15 /templates1617The application will be installed and run as Python package. This is the18recommended way to install and run Flask applications. You will see exactly16how to run ``flaskr`` later on in this tutorial. For now go ahead and create17the applications directory structure. In the next few steps you will be18creating the database schema as well as the main module.19how to run ``flaskr`` later on in this tutorial.2021For now go ahead and create the applications directory structure. In the next22few steps you will be creating the database schema as well as the main module.2324As a quick side note, the files inside of the :file:`static` folder are25available to users of the application via HTTP. This is the place where CSS and26JavaScript files go. Inside the :file:`templates` folder, Flask will look for27`Jinja2`_ templates. You will see examples of this later on.
4 unmodified lines
modified:docs/tutorial/index.rst+9 added-9 removed
1 unmodified line
23Tutorial4========56You want to develop an application with Python and Flask? Here you have7the chance to learn by example. In this tutorial, we will create a simple8microblogging application. It only supports one user that can create9text-only entries and there are no feeds or comments, but it still10features everything you need to get started. We will use Flask and SQLite11as a database (which comes out of the box with Python) so there is nothing12else you need.6Learn by example to develop an application with Python and Flask.78In this tutorial, we will create a simple blogging application. It only9supports one user, only allows text entries, and has no feeds or comments.1011While very simple, this example still features everything you need to get12started. In addition to Flask, we will use SQLite for the database, which is13built-in to Python, so there is nothing else you need.1415If you want the full source code in advance or for comparison, check out16the `example source`_.1717.. _example source:18 https://github.com/pallets/flask/tree/master/examples/flaskr/18.. _example source: https://github.com/pallets/flask/tree/master/examples/flaskr/1920.. toctree::21 :maxdepth: 222
11 unmodified lines
modified:docs/tutorial/packaging.rst+24 added-26 removed
7 unmodified lines
8tutorial you will see exactly how to extend the ``flask`` command line9interface (CLI).1011A useful pattern to manage a Flask application is to install your app12following the `Python Packaging Guide`_. Presently this involves 13creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the 14projects root directory. You also need to add an :file:`__init__.py` 15file to make the :file:`flaskr/flaskr` directory a package. After these 12following the `Python Packaging Guide`_. Presently this involves13creating two new files; :file:`setup.py` and :file:`MANIFEST.in` in the14projects root directory. You also need to add an :file:`__init__.py`15file to make the :file:`flaskr/flaskr` directory a package. After these16changes, your code structure should be::1718 /flaskr19 /flaskr
4 unmodified lines
24 schema.sql25 setup.py26 MANIFEST.in2728The content of the ``setup.py`` file for ``flaskr`` is:28Create the ``setup.py`` file for ``flaskr`` with the following content::2930.. sourcecode:: python3130 from setuptools import setup3132 setup(33 name='flaskr',
6 unmodified lines
4041When using setuptools, it is also necessary to specify any special files42that should be included in your package (in the :file:`MANIFEST.in`).43In this case, the static and templates directories need to be included,46as well as the schema. Create the :file:`MANIFEST.in` and add the47following lines::44as well as the schema.4546Create the :file:`MANIFEST.in` and add the following lines::4748 graft flaskr/templates49 graft flaskr/static50 include flaskr/schema.sql5153To simplify locating the application, add the following import statement 54into this file, :file:`flaskr/__init__.py`:52Next, to simplify locating the application, create the file,53:file:`flaskr/__init__.py` containing only the following import statement::5456.. sourcecode:: python5755 from .flaskr import app5660This import statement brings the application instance into the top-level 61of the application package. When it is time to run the application, the 62Flask development server needs the location of the app instance. This 63import statement simplifies the location process. Without it the export 64statement a few steps below would need to be 57This import statement brings the application instance into the top-level58of the application package. When it is time to run the application, the59Flask development server needs the location of the app instance. This60import statement simplifies the location process. Without the above61import statement, the export statement a few steps below would need to be62``export FLASK_APP=flaskr.flaskr``.6364At this point you should be able to install the application. As usual, it65is recommended to install your Flask application within a `virtualenv`_.69With that said, go ahead and install the application with::66With that said, from the ``flaskr/`` directory, go ahead and install the67application with::6869 pip install --editable .7073The above installation command assumes that it is run within the projects 74root directory, `flaskr/`. The `editable` flag allows editing 75source code without having to reinstall the Flask app each time you make 76changes. The flaskr app is now installed in your virtualenv (see output 71The above installation command assumes that it is run within the projects72root directory, ``flaskr/``. The ``editable`` flag allows editing73source code without having to reinstall the Flask app each time you make74changes. The flaskr app is now installed in your virtualenv (see output75of ``pip freeze``).7677With that out of the way, you should be able to start up the application.80Do this with the following commands::78Do this on Mac or Linux with the following commands in ``flaskr/``::7980 export FLASK_APP=flaskr81 export FLASK_DEBUG=true82 flask run8386(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``).85The :envvar:`FLASK_DEBUG` flag enables or disables the interactive debugger.86*Never leave debug mode activated in a production system*, because it will87allow users to execute code on the server!8889You will see a message telling you that server has started along with92the address at which you can access it.90the address at which you can access it in a browser.9192When you head over to the server in your browser, you will get a 404 error93because we don't have any views yet. That will be addressed a little later,94but first, you should get the database working.
12 unmodified lines
modified:docs/tutorial/setup.rst+35 added-31 removed
1 unmodified line
23Step 2: Application Setup Code4==============================56Now 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 the9application module are the needed import statements. After that there will be a10few lines of configuration code. For small applications like ``flaskr``, it is11possible to drop the configuration directly into the module. However, a cleaner12solution is to create a separate ``.ini`` or ``.py`` file, load that, and13import the values from there.6Next, 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 be8placed inside of the :file:`flaskr/flaskr` folder.910For 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 you12decide to create).1314The first several lines of code in the application module are the needed import15statements. After that there will be a few lines of configuration code.1617For small applications like ``flaskr``, it is possible to drop the configuration18directly into the module. However, a cleaner solution is to create a separate19``.py`` file, load that, and import the values from there.2021Here are the import statements (in :file:`flaskr.py`)::2217 # all the imports23 import os24 import sqlite320 from flask import Flask, request, session, g, redirect, url_for, abort, \21 render_template, flash2526 from flask import (Flask, request, session, g, redirect, url_for, abort,27 render_template, flash)2829The next couple lines will create the actual application instance and24initialize it with the config from the same file in :file:`flaskr.py`:30initialize it with the config from the same file in :file:`flaskr.py`::3126.. sourcecode:: python2732 app = Flask(__name__) # create the application instance :)33 app.config.from_object(__name__) # load config from this file , flaskr.py3435 # Load default config and override config from an environment variable
4 unmodified lines
40 PASSWORD='default'41 ))42 app.config.from_envvar('FLASKR_SETTINGS', silent=True)4340The :class:`~flask.Config` object works similarly to a dictionary, so it can be41updated with new values.44In the above code, the :class:`~flask.Config` object works similarly to a45dictionary, so it can be updated with new values.4647.. admonition:: Database Path4849 Operating systems know the concept of a current working directory for
11 unmodified lines
6162Usually, it is a good idea to load a separate, environment-specific63configuration file. Flask allows you to import multiple configurations and it64will use the setting defined in the last import. This enables robust61configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.65configuration setups. :meth:`~flask.Config.from_envvar` can help achieve66this. ::6763.. sourcecode:: python6468 app.config.from_envvar('FLASKR_SETTINGS', silent=True)6967Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to68a config file to be loaded. The silent switch just tells Flask to not complain69if no such environment key is set.70If you want to do this (not required for this tutorial) simply define the71environment variable :envvar:`FLASKR_SETTINGS` that points to a config file72to be loaded. The silent switch just tells Flask to not complain if no such73environment key is set.7475In addition to that, you can use the :meth:`~flask.Config.from_object`76method on the config object and provide it with an import name of a77module. Flask will then initialize the variable from that module. Note
1 unmodified line
7980The ``SECRET_KEY`` is needed to keep the client-side sessions secure.81Choose that key wisely and as hard to guess and complex as possible.8279Lastly, you will add a method that allows for easy connections to the80specified database. This can be used to open a connection on request and81also from the interactive Python shell or a script. This will come in82handy later. You can create a simple database connection through SQLite and83then tell it to use the :class:`sqlite3.Row` object to represent rows.84This allows the rows to be treated as if they were dictionaries instead of85tuples.83Lastly, add a method that allows for easy connections to the specified84database. ::8587.. sourcecode:: python8886 def connect_db():87 """Connects to the specific database."""8889 rv = sqlite3.connect(app.config['DATABASE'])90 rv.row_factory = sqlite3.Row91 return rv9293This can be used to open a connection on request and also from the94interactive Python shell or a script. This will come in handy later.95You can create a simple database connection through SQLite and then tell96it to use the :class:`sqlite3.Row` object to represent rows. This allows97the rows to be treated as if they were dictionaries instead of tuples.9899In the next section you will see how to run the application.100101Continue with :ref:`tutorial-packaging`.
modified:docs/tutorial/templates.rst+2 added-1 removed
13 unmodified lines
1415We are also using template inheritance which makes it possible to reuse16the layout of the website in all pages.1718Put the following templates into the :file:`templates` folder:18Create the follwing three HTML files and place them in the19:file:`templates` folder:2021.. _Jinja2: http://jinja.pocoo.org/docs/templates2223layout.html
90 unmodified lines
modified:docs/tutorial/views.rst+2 added-1 removed
2 unmodified lines
3Step 6: The View Functions4==========================56Now that the database connections are working, you can start writing the7view functions. You will need four of them:7view functions. You will need four of them; Show Entries, Add New Entry,8Login and Logout. Add the following code snipets to :file:`flaskr.py`.910Show Entries11------------12
106 unmodified lines