Introduction to Flask Web Development

avatar

Welcome back to another article on getting started with Python coding and this week we are going to move away a little bit from what we have been working on. In previous articles we have been showing you the core features of the Python programming language. We are going to start with something a little different in the next few articles and introduce you to the Flask web framework.

Within Python if we wanted to use the core language to create a web application, this could be done but it would not be as straight forward an easy as you might have come accustom to with your previous work in Python. Instead we can use a framework that does all the hard work for us and allows us to concentrate more on important things. If you have not heard the term framework, think of it as an extension that you install that adds a group of functions and classes specific to what you need. In this case, when using Flask, it will provide classes and functions to create our web pages by rendering our code, providing routes for url's and other things. The cool thing is, we don't really need to know much more than the Python syntax to implement these functions and classes to still use them effectively.

We have decided to use Flask in creating and working with web apps because in our opinion it is the simplest to use, while still offering a large range of configuration options. The syntax is also verify similar to the Python code we have been working with in previous articles, so it is great for new users. We will just start with the basics in this article to get you started and hopefully elaborate further in one or two more future articles.

Before You Start


Instead of installing all the modules and applications directly onto our system, we are instead going to use a Python module called virtualenv to create a virtual environment that we can install and run our code in, and then when we are finished, we can deactivate it and the underlying system will remain without any changes performed. Just as we have used to install other Python Modules using pip3 we can do the same with virtualenv

pip3 install virtualenv

We can then create a virtual environment with the following command where venv is the virtualenv module we are using and the second venv is the name:

python3 -m venv venv

We can then activate the virtual environment so we can start working in it with:

Linux/Mac:

source venv/scripts/activate

Windows:

.\\venv\\scripts\\activate

To then deactivate the virtual environment, you simply use the deactivate command.

Getting started


For this article we are going to create a basic app called flasking just to help with getting the knowledge across. Create a directory called flasking to get started and then move into the directory:

mkdir flasking; cd flasking

We installed virtualenv in the previous part of this article, so we should use it in our new project to help get you used to using it. Create a new virtualenv and then activate it ready for use:

python3 -m venv venv

source venv/scripts/activate

This is where you will install Flask onto your virtual environment. We will add some other dependencies we will most likely need down the track, so instead of simply installing Flask using pip3, we will create a requirements.txt file and add a list of Modules to install all at once.

Start by creating the requirements.txt file:

touch requirements.txt

Open the file with your text editor and add in the following three modules we want to install. For now, we will only be using the Flask module, but we will be using the other Modules later on, so I hae also added these in now to save time later:

Flask==0.10.1
Flask-SQLAlchemy==1.0
Flask-WTF==0.9.3
python-dotenv

Save the file and you should then be able to install all the Modules from one command using the new requirements.txt file you created:

pip3 install -r requirements.txt

To make sure the Flask module is now installed, we can quickly test this by opening the python3 interactive shell and running the import flask command. If you have installed Flask correctly, you should not see any errors:

Python 3.8.10 (tags/v3.8.10:3d8993a, May  3 2021, 11:48:03) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import flask

We can now create a new directory to place our application in. Create a directory named app in your current environment:

mkdir app

Now create a file named init.py. This will be the first file the application will hit and all you to define where traffic will be routed.

touch app/__init__.py

Add the following code into the file with your text editor. The first line imports the Flask module and then creates an application named app. Finally, it will import the routes we are going to create in the next section:

from flask import Flask

app = Flask(__name__)

from app import routes

Creating the routes is simple. We can start by creating the file in the app directory:

touch app/routes.py

We can now start to set up the routes for our application. The routes are the different URLs that the application will implement. These routes are written as Python functions, as you can see we have set up two routes with the function then defined below. For both the root(/) and index to then simply show the text in the browser "Hello, World!".

from app import app

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

We now need to define our application at the top level. To do this create the script named flasking.py in the route of your application directory:

touch flasking.py

All we need to add in this script is import the app module we created as part of the init.py script.

from app import app

We are almost ready to test the new Flask application, but before we run it, we need to tell flask where it is by exporting the application file we just created.

If you are using Windows, you run the following command export the values:

$Env:FLASK_APP = "flasking.py"

For Linux and Max, you use this following command:

export FLASK_APP=flasking.py

Flask also comes with a web server built in to allow you to test the code you have just created. You can do this simply by running the command, "flask run" in the command line, as we have done below:

flask run
 * Serving Flask app 'flasking.py' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

As you can see, we can now open a browser and enter in the domain 127.0.0.1:5000/ and you should now have the "Hello, World!' text visible in the browser.

To stop the development web server from running, simply enter CTRL+C to quit as it explains in the command line.

Continuing On And Introducing Templates


Just before we continue on with introducing templates, I just want to make one quick change to our work that should make it a little easier to work with. In the last part of this article we exported the FLASK_APP environment variable, before running our development web server. Instead of needing to do this every time we run our web server on a new session, we have installed the python-dotenv Module at the start of this article. This will allow use to create a file called .flaskenv which we can then add all out environment variables in, which will then be used by Flask.

Start by creating the .flaskenv file in the root of your current application:

touch .flaskenv

Open the file with your text editor and add in the following line of code:

FLASK_APP=flasking.py

Save the file and if you wanted to test this, you could deactivate your virtual environment and log out of your session, then simply activate the virtual environment again and your FLASK_APP environment variable would still be active.

As you can see below, we can expand the routes file by adding in HTML to be returned when the as part of the function defined in the app/routes.py script. Although its a simple change it shows that we can expand our functions further in Flask:

from app import app

@app.route('/')
@app.route('/index')
def index():
  return '''
<html>
  <head>
    <title>Home Page - Welcome</title>
  </head>
  <body>
    <h1>Welcome to Flasking!</h1>
  </body>
</html>'''

But instead of doing this as part of our routes.py functions, we can instead use templates to then be used by the functions in our routes.py script.

To get this working we will finish off this article with a simple example. Start by creating a new directory called templates in the app directory:

mkdir app/templates

We can now create a file called index.html file in the templates directory, that will be used by our applications. We can now open the file app/templates/index.html file with our text editor and add in all of the following HTML. As you can see, we have added in some extra values in between the title tags and the h2 heading. Flask allows you to use Jinja2 templates where we can pass variables from our code to then be rendered by our web browser:

<html>
  <head>
    <title>{{ title }} - Welcome</title>
  </head>
  <body>
    <h1>Welcome to Flasking!</h1>
    <h2>Hello, {{ user.username }}</h2>
  </body>
</html>

We can now update the app/routes.py script to now look like the following. We first need to make sure we include the renter_template function from the flask Module. This will allow us to convert the index.html template we have just created into a valid HTML and displayed in our browser. The index function now includes variables in the form of a Dictionary key value pair which will be used by our template. The final line that includes the return statement also uses the render_template function, which takes our index.html template and provides the values that need to be parsed to the template to complete the variables needed by the Jinja2 template:

from flask import render_template
from app import app

@app.route('/')
@app.route('/index')
def index():
  user = {'username': 'Vince'}
  return render_template('index.html', title='Home Page', user=user)

If you perform a "flask run" command from the command line, you will now be able to browse to this index.html page, but instead it should now also include the dynamic values specified in our template and functions.

This is just a simple example of using templates in Flask, but in our next article, we will show you how you can expand the use of templates further.

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



0
0
0.000
0 comments