Adding Features To A Python-Flask Website

Adding Features To A Python-Flask Website

Tabby Mungai

Tabby Mungai

September 27, 2023

A python website refers to a website developed using the python code. On the other hand, a flask refers to a web framework that allows the ease of web development. Coding websites can be immensely beneficial to assist programmers develop website platforms. Using code is a welcome alternative to using a website builder or website maker. Additionally, by providing addition features for your Python flask for web development this can be good coding practice as the python flask simple website can be part of your coding exercises.

In this blog, we are going to gain crucial insights into various ways additional features can be added to the Python Flask web interface. The additional features will include linking pages and the use of conditional loops. When creating additional features to the website it is important to ensure that the HTML is not part of the code (An attacker can input malicious HTML within the code). Therefore, a more suitable web framework it is important to use templates to ensure that the code is concerned with data values and not rendering.

  • Template: Refers to an HTML file containing placeholders for values that the code give at runtime.

  • Default Templating: The flask is jinja installed automatically when the flask is installed. Jinja (engine) provide flexible options that such as automatic escaping (XSS attacks) and template inheritance.

  • Inheritance: Allows one to define a base page having a common markup and then build on that base with page-specific additions.

Template Inheritance

Template inheritance allows an individual when coding to avoid code repetition. By using template inheritance the one who creates a website create a base template that contains content that has the capacity to be shared with other templates. Also, the index template can be edited to inherit from the base template. A new page that serves as the About page to provide additional information regarding the application.

Here we will create a single using a be configured to serve statistic files. Additionally, multiple pages can be created for the app that each contains a nav bar from a base template.

1. Inside the flask folder create a new folder and name it templates

2. Inside the templates folder create a file app.py using the VSCode terminal. In app.py the function render_template for loading the template and application of the named values.

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

For loading the template and application of the named values. The template comprised two placeholders “name” and “date” shown as delineated pairs of curly braces {{and}} the formatting code ought to be included directly into the file.

Base Template: The template comprises HTML components that are shared between all other templates including application title, navigation bars and footnotes.

{%extends%} is a tag used to inherit from base.html

The tag is extended by replacing the content in the base template with what is inside the content block in the preceding code block. Template inheritance is immensely used as it allows one to reuse the HTML code in another template such as base.html without the need to repeat them each time they are required.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %} {% endblock %} - FlaskApp</title>
    <style>
        nav a {
            color: #d64161;
            font-size: 3em;
            margin-left: 50px;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <nav>
        <a href="{{ url_for('index') }}">FlaskApp</a>
        <a href="#">About</a>
    </nav>
    <hr>
    <div class="content">
        {% block content %} {% endblock %}
    </div>
</body>
</html>

To Create the About Page

To create the About page add the the code below in the app.py file

#...
@app.route('/about/')
def about():
    return render_template('about.html')

app.route() decorator creates a view function about(). In the decorator, a result is returned of calling render_template() function with about.html template file name as an argument.

The about.html file has the following code

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return '<h1>Hello, World!</h1>'

@app.route('/about/')
def about():
    return '<h3>Geviton:"Bring Your Ideas To life".</h3>

Here code inherits from the base template using the extends tag

  • The content block in the base template is replaced with <h1>tag that also serves as the page title

  • <h3>tag is added regarding information about the application

With the development server running visit the following URL using your browser

http://127.0.0.1:5000/about, it is evident the way the navigation bar and part of the title are inherited from the based template

Rendering a Template and Using Variable

Using Templates in a Flask Application

  • Create index.html file

  • Tell flask about app.py using FLASK_APP environment (using the set command for window)

  • Set FLASK_ENV environment variable to development to run the application in development mode and get access to the debugger

Import datetime module from the Python standard library and edit the index() function into the app.py

#..
@app.route('/')
def hello():
    return render_template('index.html', utc_dt=datetime.datetime.utcnow())

@app.route('/about/')
def about():
    return render_template('about.html')

In the HTML file edit and add <h3>{{utc_dt}}</h3>, this particular edit adds H3 heading with special {{…}} delimiter to print the value of the utc_dt variable.

#...
<h3>{{ utc_dt }}</h3>
#...

The content block contains<h1>tag with text index inside a title block in the base.html template with the index making the complete tile Index_FlaskApp

This is done to avoid repeating the same text twice because it acts both as a title and heading below the navigation bar inherited from the base.

Then you have a few more headings:

  • one <h1>with text HelloWorld!

  • <h2> and <h3>with the value utc_dt variable


Linking Between Pages

For this step, you will learn how to link pages in your templates using url_for() helper function. Two links are added to the navigation bar in the base template.

i) Index page

ii) About page

#...
<body>
    <nav>
        <a href="{{ url_for('hello') }}"> Geviton FlaskApp</a>
        <a href="{{ url_for('comments') }}">Comments</a>
        <a href="{{ url_for('about') }}">About</a>
    </nav>
    <hr>
    <div class="content">
        {% block content %} {% endblock %}
    </div>
</body>
</html>

From the code: The first URL links to the route of hello() and the second URL links the route of the about() function within the index page url_for() function builds URLs and helps manage URLs

When the URLs are hard-coded editing the routes breaks the link. However, by using url_for() one can edit routes and guarantee the link works in an appropriate manner. Additionally, url_for() function takes care of other things like escaping special characters.

This section enabled you on how to use url_for() function to link to other routes in your templates.

Using Conditional and Loops

  • if statements found in the templates control what to display depending on certain conditions

  • for loops to go through Python lists and display each item in the list create a new page that displays comments in a list. (Comments with an odd index number will be displayed with a green background)


    @app.route('/comments/') 
    def comments(): 
        comments = ['This is the first comment.', 
                    'This is the second comment.', 
                    'This is the third comment.', 
                    'This is the fourth comment.' 
                    ] 
     
        return render_template('comments.html', comments=comments)

The route above illustrates a Python list called comments comprising four items. (Comments are designed to be obtained from online users)

You return a template file referred to as comments, html in the last line is passing a variable called comments containing the list template file.

{%block content%}{%block content%}{%end block%}

The block can be replaced by content depending on the child template (a template that inherits from base.html) that overrides it. Now that a based template has been created it’s time to take advantage of inheritance.

The file comment.html contains the code provided

{% extends 'base.html' %}

{% block content %}
    <h1>{% block title %} Comments {% endblock %}</h1>
    <div style="width: 50%; margin: auto">
        {% for comment in comments %}
            {% if loop.index % 2 == 0 %}
                {% set bg_color = '#F97316' %}
            {% else %}
                {% set bg_color = '#0B8070' %}
            {% endif %}

            <div style="padding: 10px;
                 background-color: {{ loop.cycle('#0B8070', '#F97316') }}; 
                 margin: 20px">
                <p>#{{ loop.index }}</p>
                <p style="font-size: 24px">{{ comment }}</p>
            </div>
        {% endfor %}
    </div>
{