So far, we’ve set up our project, having installed flask, set up a virtual environment and set up a remote repository. We’re now going to start work on the project itself.
3. Creating the home or index page
3.1 Creating app.py for the routing
The next step is to start working on the actual app (which will be a shopping list). To do this, we will create a new app (app.py) and then tell it where to find templates to render the webpage it is serving. The first thing to do is to create a new file called app.py and put this code in it:
from flask import Flask, render_template
app = Flask(__name__)
@app.route(‘/’)
def index():
return render_template(‘index.html’)
This assigns app to the name of our app, and then creates a function called index which calls the function render_template on index.html, and returns the outcome. Render_template is a function that uses template HTML files. These are stored in the templates folder
which we will create.
The @app.route function is a view function that handles requests to anything on the / route.
3.2 The template and HTML code
First we will create templates/index.html and put this code in there:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<link rel=”stylesheet” href=”{{ url_for(‘static’, filename= ‘css/style.css’) }}”>
<title>FlaskBlog</title>
</head>
<body>
<h1>Welcome to FlaskBlog</h1>
</body>
</html>
3.3 Styling the HTML code
But what about styling the HTML code? We can create a file called /static/css/style.css. Put this code in here:
h1 {
border: 2px #eee solid;
color: brown;
text-align: center;
padding: 10px;
}
3.4 Running the app again
Before testing it out, we also need to make sure that we set the right app.
export FLASK_APP=app
Now, when we run our app, we should have a styled index page.