Now we’ll make the base code to get our Flask app working. We start by making an
app.py file that will contain the Flask initialization:
# app.py import locale from flask import Flask import logging locale.setlocale(locale.LC_TIME, locale.getlocale()) logging.basicConfig() app = Flask(__name__) app.config.from_object('config') @app.route('/') def index(): return "Hello World"
In this file we setup the basic logging utilities and we set some locale config for datetime.
The important part here is the declaration of the
app variable which is an instance of Flask. This will manage all our web requests. With the
app.config.from_object('config') instruction we tell Flask to load all the configurations of our app from a config file, so now we need to make the
# config.py SECRET_KEY = 'very secret string!'
This file is small right now, we’ll add some more lines as we add database access to our app.
The only thing missing that is needed in order to run our raw webapp is way to start it, so we make a
run.py file with only these two lines of code:
# run.py from app import app app.run(debug=True)
Now we are ready to test if everything is working. Go to the shell and run our last created file:
(venv)$ python run.py WARNING:werkzeug: * Debugger is active!
Now our app is up and running, and we should be able to get the Hello World message in the browser by hitting the
control + cto stop the wesberver.
Now that we have our Flask app running, let’s make it a little more organized. At this point our folder structure should look like this:
tempy_app\ venv\ static\ templates\ requirements.txt app.py run.py config.py
We’ll add one empty file that will contain our database models:
(venv)$ touch models.py
and we move the controllers code to a new file. First create the
controllers.py file and add the controller code from
from app import app @app.route('/') def index(): return "Hello World"
..and replace the controller code in
app.py with an import of this new file.
app.py will now look like this:
# app.py import locale from flask import Flask import logging locale.setlocale(locale.LC_TIME, locale.getlocale()) logging.basicConfig() app = Flask(__name__) app.config.from_object('config') import models import controllers
Now that we have the basic app structure we need to add a database to our app in the next section.