Skip to content
Myr

Grammatical fixes in Foreword and Tutorial

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

authored by Kevin Yap · committed by Kevin Yap · parent 475d707 · Browse files · 12 files+98 added−96 removed
This commit

State

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

Diff stats

12 files+98 added−96 removed

  • other:+98 added−96 removed

12 files+98 added−96 removed

modified:docs/tutorial/css.rst+2 added-2 removed
2 unmodified lines
3Step 7: Adding Style4====================56Now that everything else works, it's time to add some style to the7application. Just create a stylesheet called :file:`style.css` in the :file:`static`8folder we created before:7application. Just create a stylesheet called :file:`style.css` in the8:file:`static` folder we created before:910.. sourcecode:: css1112 body { font-family: sans-serif; background: #eee; }
19 unmodified lines
modified:docs/tutorial/dbcon.rst+13 added-13 removed
2 unmodified lines
3Step 3: Database Connections4----------------------------56We have created a function for establishing a database connection with7`connect_db` but by itself that's not particularly useful. Creating and7`connect_db`, but by itself, that's not particularly useful. Creating and8closing database connections all the time is very inefficient, so we want9to keep it around for longer. Because database connections encapsulate a10transaction we also need to make sure that only one request at the time11uses the connection. So how can we elegantly do that with Flask?10transaction, we also need to make sure that only one request at the time11uses the connection. How can we elegantly do that with Flask?1213This is where the application context comes into play. So let's start13This is where the application context comes into play, so let's start14there.1516Flask provides us with two contexts: the application context and the17request context. For the time being all you have to know is that there18are special variables that use these. For instance the17request context. For the time being, all you have to know is that there18are special variables that use these. For instance, the19:data:`~flask.request` variable is the request object associated with20the current request, whereas :data:`~flask.g` is a general purpose21variable associated with the current application context. We will go into22the details of this a bit later.2324For the time being all you have to know is that you can store information24For the time being, all you have to know is that you can store information25safely on the :data:`~flask.g` object.2627So when do you put it on there? To do that you can make a helper28function. The first time the function is called it will create a database29connection for the current context and successive calls will return the28function. The first time the function is called, it will create a database29connection for the current context, and successive calls will return the30already established connection::3132 def get_db():33 """Opens a new database connection if there is none yet for the
4 unmodified lines
38 return g.sqlite_db394041So now we know how to connect, but how do we properly disconnect? For42that flask provides us with the :meth:`~flask.Flask.teardown_appcontext`42that, Flask provides us with the :meth:`~flask.Flask.teardown_appcontext`43decorator. It's executed every time the application context tears down::4445 @app.teardown_appcontext46 def close_db(error):
1 unmodified line
48 if hasattr(g, 'sqlite_db'):49 g.sqlite_db.close()5051Functions marked with :meth:`~flask.Flask.teardown_appcontext` are called52every time the app context tears down. So what does this mean?53Essentially the app context is created before the request comes in and is52every time the app context tears down. What does this mean?53Essentially, the app context is created before the request comes in and is54destroyed (torn down) whenever the request finishes. A teardown can55happen because of two reasons: either everything went well (the error56parameter will be ``None``) or an exception happened in which case the error56parameter will be ``None``) or an exception happened, in which case the error57is passed to the teardown function.5859Curious about what these contexts mean? Have a look at the60:ref:`app-context` documentation to learn more.
18 unmodified lines
modified:docs/tutorial/dbinit.rst+20 added-20 removed
3 unmodified lines
4=============================56As outlined earlier, Flaskr is a database powered application, and more7precisely, it is an application powered by a relational database system. Such8systems need a schema that tells them how to store that information. So9before starting the server for the first time it's important to create8systems 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 the12Such a schema can 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 we provide the path to the database which can introduce17The downside of this is that it requires the ``sqlite3`` command to be18installed, which is not necessarily the case on every system. This also19requires 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 and hook it into the :command:`flask` command24that initializes the database. Let me show you the code first. Just add25this function below the `connect_db` function in :file:`flaskr.py`::23To do this, we can create a function and hook it into the :command:`flask`24command that initializes the database. Let me show you the code first. Just25add this function below the `connect_db` function in :file:`flaskr.py`::2627 def init_db():28 db = get_db()29 with app.open_resource('schema.sql', mode='r') as f:
6 unmodified lines
36 init_db()37 print 'Initialized the database.'3839The ``app.cli.command()`` decorator registers a new command with the40:command:`flask` script. When the command executes Flask will automatically40:command:`flask` script. When the command executes, Flask will automatically41create a application context for us bound to the right application.42Within the function we can then access :attr:`flask.g` and other things as42Within the function, we can then access :attr:`flask.g` and other things as43we would expect. When the script ends, the application context tears down44and the database connection is released.4546We want to keep an actual functions around that initializes the database47though so that we can easily create databases in unittests later. (For46We want to keep an actual functions around that initializes the database,47though, so that we can easily create databases in unit tests later on. (For48more information see :ref:`testing`.)4950The :func:`~flask.Flask.open_resource` method of the application object51is a convenient helper function that will open a resource that the52application provides. This function opens a file from the resource53location (your `flaskr` folder) and allows you to read from it. We are53location (your ``flaskr`` folder) and allows you to read from it. We are54using this here to execute a script on the database connection.5556The connection object provided by SQLite can give us a cursor object.57On that cursor there is a method to execute a complete script. Finally we58only have to commit the changes. SQLite 3 and other transactional57On that cursor, there is a method to execute a complete script. Finally, we58only have to commit the changes. SQLite3 and other transactional59databases will not commit unless you explicitly tell it to.6061Now it is possible to create a database with the :command:`flask` script::61Now, it is possible to create a database with the :command:`flask` script::6263 flask --app=flaskr initdb64 Initialized the database.6566.. admonition:: Troubleshooting6768 If you get an exception later that a table cannot be found check that69 you did execute the `initdb` command and that your table names are70 correct (singular vs. plural for example).68 If you get an exception later on stating that a table cannot be found, check69 that you did execute the ``initdb`` command and that your table names are70 correct (singular vs. plural, for example).7172Continue with :ref:`tutorial-views`
modified:docs/tutorial/folders.rst+6 added-6 removed
8 unmodified lines
9 /flaskr10 /static11 /templates1213The `flaskr` folder is not a python package, but just something where we14drop our files. We will then put our database schema as well as main module15into this folder. It is done in the following way. The files inside13The ``flaskr`` folder is not a Python package, but just something where we14drop our files. Later on, we will put our database schema as well as main15module into this folder. It is done in the following way. The files inside16the :file:`static` folder are available to users of the application via HTTP.17This is the place where css and javascript files go. Inside the18:file:`templates` folder Flask will look for `Jinja2`_ templates. The19templates you create later in the tutorial will go in this directory.17This is the place where CSS and Javascript files go. Inside the18:file:`templates` folder, Flask will look for `Jinja2`_ templates. The19templates you create later on in the tutorial will go in this directory.2021Continue with :ref:`tutorial-schema`.2223.. _Jinja2: http://jinja.pocoo.org/
modified:docs/tutorial/index.rst+3 added-3 removed
2 unmodified lines
3Tutorial4========56You want to develop an application with Python and Flask? Here you have7the chance to learn that by example. In this tutorial we will create a8simple microblog application. It only supports one user that can create7the 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 database which comes out of the box with Python, so there is nothing11as a database (which comes out of the box with Python) so there is nothing12else you need.1314If you want the full source code in advance or for comparison, check out15the `example source`_.
17 unmodified lines
modified:docs/tutorial/introduction.rst+11 added-11 removed
1 unmodified line
23Introducing Flaskr4==================56We will call our blogging application flaskr here, feel free to choose a7less web-2.0-ish name ;) Basically we want it to do the following things:6We will call our blogging application flaskr, but feel free to choose your own7less Web-2.0-ish name ;) Essentially, we want it to do the following things:891. let the user sign in and out with credentials specified in the91. Let the user sign in and out with credentials specified in the10 configuration. Only one user is supported.112. when the user is logged in they can add new entries to the page112. When the user is logged in, they can add new entries to the page12 consisting of a text-only title and some HTML for the text. This HTML13 is not sanitized because we trust the user here.143. the page shows all entries so far in reverse order (newest on top) and15 the user can add new ones from there if logged in.143. The index page shows all entries so far in reverse chronological order15 (newest on top) and the user can add new ones from there if logged in.1617We will be using SQLite3 directly for that application because it's good18enough for an application of that size. For larger applications however19it makes a lot of sense to use `SQLAlchemy`_ that handles database20connections in a more intelligent way, allows you to target different17We will be using SQLite3 directly for this application because it's good18enough for an application of this size. For larger applications, however,19it makes a lot of sense to use `SQLAlchemy`_, as it handles database20connections in a more intelligent way, allowing you to target different21relational databases at once and more. You might also want to consider22one of the popular NoSQL databases if your data is more suited for those.2324Here a screenshot from the final application:24Here a screenshot of the final application:2526.. image:: ../_static/flaskr.png27 :align: center28 :class: screenshot
5 unmodified lines
modified:docs/tutorial/schema.rst+4 added-4 removed
1 unmodified line
23Step 1: Database Schema4=======================56First we want to create the database schema. Only a single table is needed7for this application and we only want to support SQLite so creating the6First, we want to create the database schema. Only a single table is needed7for this application and we only want to support SQLite, so creating the8database schema is quite easy. Just put the following contents into a file9named `schema.sql` in the just created `flaskr` folder:1011.. sourcecode:: sql
4 unmodified lines
16 title text not null,17 'text' text not null18 );1920This schema consists of a single table called `entries` and each row in21this table has an `id`, a `title` and a `text`. The `id` is an20This schema consists of a single table called ``entries``. Each row in21this table has an ``id``, a ``title``, and a ``text``. The ``id`` is an22automatically incrementing integer and a primary key, the other two are23strings that must not be null.2425Continue with :ref:`tutorial-setup`.
modified:docs/tutorial/setup.rst+26 added-24 removed
1 unmodified line
23Step 2: Application Setup Code4==============================56Now that we have the schema in place we can create the application module.7Let's call it flaskr.py. We will place this file inside the flaskr folder.8We will begin by adding the imports we need and by adding the config6Now that we have the schema in place, we can create the application module.7Let's call it ``flaskr.py``. We will place this file inside the ``flaskr``8folder. We will begin by adding the imports we need and by adding the config9section. For small applications, it is possible to drop the configuration10directly into the module, and this is what we will be doing here. However11a cleaner solution would be to create a separate ``.ini`` or ``.py`` file and12load that or import the values from there.10directly into the module, and this is what we will be doing here. However,11a cleaner solution would be to create a separate ``.ini`` or ``.py`` file,12load that, and import the values from there.1314First we add the imports in :file:`flaskr.py`::14First, we add the imports in :file:`flaskr.py`::1516 # all the imports17 import os18 import sqlite319 from flask import Flask, request, session, g, redirect, url_for, abort, \20 render_template, flash2122Next we can create our actual application and initialize it with the23config from the same file, in :file:`flaskr.py`::22Next, we can create our actual application and initialize it with the23config from the same file in :file:`flaskr.py`::2425 # create our little application :)26 app = Flask(__name__)27 app.config.from_object(__name__)
6 unmodified lines
34 PASSWORD='default'35 ))36 app.config.from_envvar('FLASKR_SETTINGS', silent=True)3738The :class:`~flask.Config` object works similar to a dictionary so we38The :class:`~flask.Config` object works similarly to a dictionary so we39can update it with new values.4041.. admonition:: Database Path4243 Operating systems know the concept of a current working directory for44 each process. Unfortunately you cannot depend on this in web44 each process. Unfortunately, you cannot depend on this in web45 applications because you might have more than one application in the46 same process.4748 For this reason the ``app.root_path`` attribute can be used to49 get the path to the application. Together with the ``os.path`` module50 files can then easily be found. In this example we place the49 get the path to the application. Together with the ``os.path`` module,50 files can then easily be found. In this example, we place the51 database right next to it.5253 For a real-work application it's recommended to use53 For a real-world application, it's recommended to use54 :ref:`instance-folders` instead.5556Usually, it is a good idea to load a separate, environment specific56Usually, it is a good idea to load a separate, environment-specific57configuration file. Flask allows you to import multiple configurations and it58will use the setting defined in the last import. This enables robust59configuration setups. :meth:`~flask.Config.from_envvar` can help achieve this.6061 app.config.from_envvar('FLASKR_SETTINGS', silent=True)61.. code-block:: python6263 app.config.from_envvar('FLASKR_SETTINGS', silent=True)6465Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to66a config file to be loaded. The silent switch just tells Flask to not complain67if no such environment key is set.6867In addition to that you can use the :meth:`~flask.Config.from_object`69In addition to that, you can use the :meth:`~flask.Config.from_object`70method on the config object and provide it with an import name of a71module. Flask will then initialize the variable from that module. Note70that in all cases only variable names that are uppercase are considered.72that in all cases, only variable names that are uppercase are considered.7374The ``SECRET_KEY`` is needed to keep the client-side sessions secure.75Choose that key wisely and as hard to guess and complex as possible.7675We will also add a method that allows for easily connecting to the76specified database. This can be used to open a connection on request and77We will also add a method that allows for easy connections to the78specified database. This can be used to open a connection on request and79also from the interactive Python shell or a script. This will come in80handy later. We create a simple database connection through SQLite and81then tell it to use the :class:`sqlite3.Row` object to represent rows.82This allows us to treat the rows as if they were dictionaries instead of
6 unmodified lines
89 rv = sqlite3.connect(app.config['DATABASE'])90 rv.row_factory = sqlite3.Row91 return rv9291With that out of the way you should be able to start up the application93With that out of the way, you should be able to start up the application94without problems. Do this with the following command::9596 flask --app=flaskr --debug run97
3 unmodified lines
101102You will see a message telling you that server has started along with103the address at which you can access it.104103When you head over to the server in your browser you will get an 404104page not found error because we don't have any views yet. But we will105focus on that a little later. First we should get the database working.105When you head over to the server in your browser, you will get a 404 error106because we don't have any views yet. We will focus on that a little later,107but first, we should get the database working.108109.. admonition:: Externally Visible Server110111 Want your server to be publicly available? Check out the
4 unmodified lines
modified:docs/tutorial/templates.rst+3 added-3 removed
1 unmodified line
23Step 6: The Templates4=====================56Now we should start working on the templates. If we request the URLs now7we would only get an exception that Flask cannot find the templates. The6Now we should start working on the templates. If we were torequest the URLs7now, we would only get an exception that Flask cannot find the templates. The8templates are using `Jinja2`_ syntax and have autoescaping enabled by9default. This means that unless you mark a value in the code with10:class:`~flask.Markup` or with the ``|safe`` filter in the template,11Jinja2 will ensure that special characters such as ``<`` or ``>`` are
75 unmodified lines
8788login.html89----------9091Finally the login template which basically just displays a form to allow91This is the login template, which basically just displays a form to allow92the user to login:9394.. sourcecode:: html+jinja95
16 unmodified lines
modified:docs/tutorial/testing.rst+1 added-1 removed
4 unmodified lines
56Now that you have finished the application and everything works as7expected, it's probably not a bad idea to add automated tests to simplify8modifications in the future. The application above is used as a basic9example of how to perform unittesting in the :ref:`testing` section of the9example of how to perform unit testing in the :ref:`testing` section of the10documentation. Go there to see how easy it is to test Flask applications.
modified:docs/tutorial/views.rst+6 added-6 removed
1 unmodified line
23Step 5: The View Functions4==========================56Now that the database connections are working we can start writing the6Now that the database connections are working, we can start writing the7view functions. We will need four of them:89Show Entries10------------
3 unmodified lines
14The one with the highest id (the newest entry) will be on top. The rows15returned from the cursor look a bit like tuples because we are using16the :class:`sqlite3.Row` row factory.1718The view function will pass the entries as dicts to the18The view function will pass the entries as dictionaries to the19:file:`show_entries.html` template and return the rendered one::2021 @app.route('/')22 def show_entries():
5 unmodified lines
28Add New Entry29-------------3031This view lets the user add new entries if they are logged in. This only32responds to ``POST`` requests, the actual form is shown on the33`show_entries` page. If everything worked out well we will32responds to ``POST`` requests; the actual form is shown on the33`show_entries` page. If everything worked out well, we will34:func:`~flask.flash` an information message to the next request and35redirect back to the `show_entries` page::3637 @app.route('/add', methods=['POST'])
21 unmodified lines
59----------------6061These functions are used to sign the user in and out. Login checks the62username and password against the ones from the configuration and sets the63`logged_in` key in the session. If the user logged in successfully, that63`logged_in` key for the session. If the user logged in successfully, that64key is set to ``True``, and the user is redirected back to the `show_entries`65page. In addition, a message is flashed that informs the user that he or66she was logged in successfully. If an error occurred, the template is67notified about that, and the user is asked again::
11 unmodified lines
79 flash('You were logged in')80 return redirect(url_for('show_entries'))81 return render_template('login.html', error=error)8283The logout function, on the other hand, removes that key from the session83The `logout` function, on the other hand, removes that key from the session84again. We use a neat trick here: if you use the :meth:`~dict.pop` method85of the dict and pass a second parameter to it (the default), the method86will delete the key from the dictionary if present or do nothing when that87key is not in there. This is helpful because now we don't have to check
11 unmodified lines
modified:docs/foreword.rst+3 added-3 removed
7 unmodified lines
8What does "micro" mean?9-----------------------1011“Micro” does not mean that your whole web application has to fit into a single12Python file, although it certainly can. Nor does it mean that Flask is lacking12Python file (although it certainly can), nor does it mean that Flask is lacking13in functionality. The "micro" in microframework means Flask aims to keep the14core simple but extensible. Flask won't make many decisions for you, such as15what database to use. Those decisions that it does make, such as what16templating engine to use, are easy to change. Everything else is up to you, so
10 unmodified lines
27Configuration and Conventions28-----------------------------2930Flask has many configuration values, with sensible defaults, and a few31conventions when getting started. By convention templates and static files are31conventions when getting started. By convention, templates and static files are32stored in subdirectories within the application's Python source tree, with the33names :file:`templates` and :file:`static` respectively. While this can be changed you33names :file:`templates` and :file:`static` respectively. While this can be changed, you34usually don't have to, especially when getting started.3536Growing with Flask37------------------
20 unmodified lines