Web Development Using Flask - Part 2

in STEMGeeks4 months ago (edited)

I am not sure how many specific articles we will be posting on Flask Web Development, but for now this is part two as we are expanding the knowledge we started with in our previous article.

Our last post introducting Flask web development can be found at the following here

In this article we are hoping to clarify the routing the Flask uses to allow requests to flow through to the correct page and we will also bring you some more information on the use of templates and the way they can be used to make sure your pages are all consistently displayed.

NOTE: So far we've been the Flask development server. This helps provide a lot of great features for debugging during development, however, the development server is only intended for development. It should not be used in production. We'll dive more into this on a later article.

Flask Routing


We will start with a deeper explanation routing by providing a new example to work through. We will talk about web applications, the term 'routing' refers to the synchronization of what is displayed to the user with the address (URL) in the web browser. For example, how does our application know to display a certain page when a user is at the / (or root) location of the web site.

Start by creating a new directory where our application will live in. Call the directory flask-route as we have below and create a new virtual environment as well:

mkdir flask-route

python3 -m venv venv

source venv/bin/activate

Create a new requirements.txt file where we can add in all the required dependencies we need, including some others we may not get round to using just yet.

touch requirements.txt

Add in the following Modules:

Click==7.0
Flask==1.1.1
itsdangerous==1.1.0
Jinja2==2.10.3
MarkupSafe==1.1.1
Werkzeug==0.16.0

Save the requirements.txt file and then run pip3 to install all the dependencies:

pip3 install -r requirements.txt

As usual, when we create our new app, we will start by creating the app.py file to add in our code:

touch app.py

Open the app.py file with your text editor and add in the following code below. We start by importing the Flask module into our code and then we have created two basic routes. The first is the root of the web page(/) and the second is when the user types in "/about" to get details about the web page they are using:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "Hello World!"

@app.route('/about')
def about():
    return '<h2>About this application...</h2>'

We can now run our development server by first exporting the FLASK_APP variable and then running "flask run" from the command line as we have below:

export FLASK_APP=app.py

flask run

If everything has worked as it should, we should be able to open a web browser and browse to "localhost:5000/" to show the "Hello World!" message, and then to "localhost:5000/about" to then see the about page for our web application.

The code that we created above allowed us to define the route using the @app.route() function. We then define the function that is run, when a user accesses these routes. These are also known as view functions as it returns a response to the web browser

Our first route is in the above is the index function which is bound to the "/" route, with the index function then presents "Hello World". We could list more than one route if we wanted to. For example, under the first route of "/", we could also ad @app.route('/something_else") and when someone used this in their domain, they would also see the "Hello World!" message.

A route is also able to accept different methods. By default we are using the GET method which will simply return a response for the user, and this does not need to be defined when we define our route. We also can define POST, PUT, DELETE methods to perform different tasks and they need to be added to the route so that Flask will know what is then needed as part of the functions return.

In the following example where we add variables to our routes, we will also add methods=['GET'] to define the method as well, as an example on how this is done.

Open the app.py script again and add the following route to the bottom of the file. When we define the route, the url also includes the <user_name> which will be added dynamically when we call the url. In the function we then specify the words to be used as part of the page provided to the web browser.

@app.route('/hello/<user_name>')
def hello_message(user_name, methods=['GET'] ):
    return f'<h1>Hello {(user_name)}!</h1>'

If you save the script and then run the Flask development web server we can user a url like the following: localhost:5000/hello/vince

And the name we provided in the url will then be provided in the browser.

Expanding Templates


We started using Flask templates in our previous article but just touched on the basics. Here were are going to expand things a little further to show you how to use a base template and limit the amount of your you need to be doing when running you app from Flask.

By using templates in our Flask app we can can use static HTML template files seperate our structure and our content in our app, we will also be able to use programming concepts like variables, conditionals, and for loops that will work directly in the HTML to manipulate the final rendered output.

To do this we will make some changes to the app.py script first and then add in our templates. Open app.py script and set it up like the following:

NOTE: Make sure you add the extra values to be imported at the start of the script as well

from flask import Flask, render_template

app = Flask(__name__)

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

@app.route('/about')
def about():
    return render_template('about.html', version="0.0.1")

@app.route('/hello/<message>')
def hello_message(message):
    return f'<h1>Welcome {(message)}!</h1>'

As you can see, we are now importing the render_template module at the start of our script, this will turn our templates into HTML code the browser will be able to understand. The index and about routes will now no longer have HTML being returned, but instead, will use the render_template function to return the template that will be used.

We can now start working on our templates. First, start by creating a directory all our templates can be stored in:

mkdir templates

Now create the file for our index and about templates:

touch templates/index.html templates/about.html

Open the templates/index.html file and add in the simple HTML code below

<h1>Welcome to the Flasking App!</h1>

Now do the same with the templates/about.html file:

<h1>About</h1>
<br>
<h2>This is version { { version } } of the Flasking App.</h2>

We can now run our development web server and see the browser will now display the pages we have set up in our templates file. It will also fill in the version for our about.html page as well. We can expand this even further by creating a base template that all the other pages will use.

Start by creating the base.html file in the templates directory:

touch templates/base.html

Open the file with your text editor and add in the following HTML code. As you can see inside the body of the code, you will see the {% block content %} tag that will allow use to add details from our templates:

<!DOCTYPE html>
<html lang="en">
  <head>
    (html comment removed:  Required meta tags )
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Welcome To The Flasking App</title>
  </head>

  <body>
    <header>
      <h1>Flasking App</h1>
    </header>

    <main>
      (html comment removed:  child template )
      {% block content %}
      {% endblock %}
    </main>
  </body>
</html>

Now open the templates/index.html file and amend it to now look like the following code. You will notice the start of the file has the {% extends "base.html" %} tag, which is similar to an import statement in our other code files. It will take the base.html file and then add in the extra data we have in place from this file:

{% extends "base.html" %}

{% block content %}
<h1>Welcome to the Flasking App!</h1>
{% endblock %}

Now open the templates/about.html file and set up the file to look like the code we have below. As you can see we are again using the base.html template but there is a lot of extra details in our block. We also have an if statement that looks for the version variable and if it is not present, it will display a System Error on the screen:

{% extends "base.html" %}

{% block content %}
<h1>About</h1>
<br>
{% if version %}
  <h2>This is version {{ version }} of the Flasking App.</h2>
{% else %}
  <h2>System Error!</h2>
{% endif %}
{% endblock %}

When you run the web server now, you'll see a lot more displayed on the browser as each of our pages is now using the base.html as part of their HTML. This means that any changes that need to be made to the look and feel of our site only needs to be made to the base.html and not the rest of the templates.

I hope you can now see the extra power you have now by using templates. This also brings us to the end of this article, but don't worry there is still a lot of work to be done with Flask, so stay tuned for more articles to get started using Flask.

Found this post useful? Kindly tap the up vote button below! :)

About The Author

I am a DevOps Engineer, Endurance Athlete and Author. As a DevOps Engineer I specialize in Linux and Open Source Applications. Particularly interested in Search Marketing and Analytic’s, and is currently developing my skills in devops, continuous integration, security, and development(Python).

Posted with STEMGeeks

Sort:  

Congratulations @run.vince.run! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You have been a buzzy bee and published a post every day of the week

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Check out the last post from @hivebuzz:

Hive Power Up Day - June 1st 2021 - Hive Power Delegation
Support the HiveBuzz project. Vote for our proposal!

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider supporting our funding proposal, approving our witness (@stem.witness) or delegating to the @stemsocial account (for some ROI).

Please consider using the STEMsocial app app and including @stemsocial as a beneficiary to get a stronger support. 
 

Please accept my delegation of 400.00 Hive...Its all I can afford right now, but really appreceate your work @steemstem