Skip to content
Myr

setup.rst

This file

Path

docs/tutorial/setup.rst

105 lines · 4.2 KiB

Last changed by

Changed the wording of some sentences there were difficult to understand.Reetta Vaahtorantabefore adoption0d648fa

History of this file

Take it

1.. _tutorial-setup: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 flask folder. 8We will begin by adding the imports we need and by adding the config section.9For small applications, it is possible to drop the configuration directly into 10the module, and this is what we will be doing here. However a cleaner solution would be to create a separate `.ini` or `.py` file and load that or import the11values from there.1213First we add the imports in `flaskr.py`::1415    # all the imports16    import sqlite317    from flask import Flask, request, session, g, redirect, url_for, abort, \18         render_template, flash1920Next we can create our actual application and initialize it with the21config from the same file, in `flaskr.py`::2223    # create our little application :)24    app = Flask(__name__)25    app.config.from_object(__name__)2627    # Load default config and override config from an environment variable28    app.config.update(dict(29        DATABASE='/tmp/flaskr.db',30        DEBUG=True,31        SECRET_KEY='development key',32        USERNAME='admin',33        PASSWORD='default'34    ))35    app.config.from_envvar('FLASKR_SETTINGS', silent=True)3637The :class:`~flask.Config` object works similar to a dictionary so we38can update it with new values.3940.. admonition:: Windows4142    If you are on Windows, replace `/tmp/flaskr.db` with a different writeable43    path of your choice, in the configuration and for the rest of this44    tutorial.4546Usually, it is a good idea to load a separate, environment specific47configuration file.  Flask allows you to import multiple configurations and it 48will use the setting defined in the last import. This enables robust 49configuration setups.  :meth:`~flask.Config.from_envvar` can help achieve this. 50    51    app.config.from_envvar('FLASKR_SETTINGS', silent=True)5253Simply define the environment variable :envvar:`FLASKR_SETTINGS` that points to 54a config file to be loaded.  The silent switch just tells Flask to not complain 55if no such environment key is set.5657In addition to that you can use the :meth:`~flask.Config.from_object`58method on the config object and provide it with an import name of a59module.  Flask will the initialize the variable from that module.  Note60that in all cases only variable names that are uppercase are considered.6162The ``SECRET_KEY`` is needed to keep the client-side sessions secure.63Choose that key wisely and as hard to guess and complex as possible.  The64debug flag enables or disables the interactive debugger.  *Never leave65debug mode activated in a production system*, because it will allow users to66execute code on the server!6768We will also add a method that allows for  easily connecting to the specified database.  This can be used to open a connection on request and also from the interactive Python shell or a script.  This will come in handy later.  We create a69simple database connection through SQLite and then tell it to use the70:class:`sqlite3.Row` object to represent rows.  This allows us to treat71the rows as if they were dictionaries instead of tuples.7273::7475    def connect_db():76        """Connects to the specific database."""77        rv = sqlite3.connect(app.config['DATABASE'])78        rv.row_factory = sqlite3.Row79        return rv8081Finally we just add a line to the bottom of the file that fires up the82server if we want to run that file as a standalone application::8384    if __name__ == '__main__':85        app.run()8687With that out of the way you should be able to start up the application88without problems.  Do this with the following command::8990   python flaskr.py9192You will see a message telling you that server has started along with93the address at which you can access it.9495When you head over to the server in your browser you will get an 40496page not found error because we don't have any views yet.  But we will97focus on that a little later.  First we should get the database working.9899.. admonition:: Externally Visible Server100101   Want your server to be publicly available?  Check out the102   :ref:`externally visible server <public-server>` section for more103   information.104105Continue with :ref:`tutorial-dbcon`.