Python Web Development With Flask

Learning with FlaskTask

Bello Mubarak
CodebagNG
11 min readDec 17, 2017

--

FLASK

Flask is a Python web application framework developed by an international group of Python enthusiasts named Pocco led by Armin Ronacher. Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Flask is often referred to as a micro framework since it aims to keep the core of an application simple yet extensible and it does not have built-in abstraction layer for database handling, nor does it have form a validation support. Instead, Flask supports the extensions to add such functionality to the application.

INTRODUCING FlaskTask

FlaskTask is a very simple and basic web App powered by Flask and its dependencies. Its function is simple — save a task for the user, and display a list of the user’s saved tasks. We shall discuss some basics of web programming with Flask while building FlaskTask.

Now, let’s get started!

1. INSTALLING FLASK AND ITS DEPENDENCIES

Flask supports versions 2.x (2.6 onward) and 3.x (3.3 onward). Installing Flask and its dependencies only require you to run a single command from your terminal (command prompt on Windows), and you get Flask installed, together with all the dependencies. However, it is advisable to install Flask in a virtual environment, to avoid compatibility and dependencies issues.

Install VirtualEnv

If you don’t have virtualenv installed previously, now is the time to do so.

Create A Virtual Environment And Activate It

Once virtualenv is successfully installed, you can now create a virtual environment which will be the home to your Flask installation. Upon successful creation, activate the virtual environment and run this command in your terminal:

This installs the latest version of Flask and its dependencies in your newly created virtual environment, so you don’t have to worry about separately installing dependencies. Ensure that the installation is successful, and you’re ready to build FlaskTask.

2. FLASK APPS DIRECTORY STRUCTURE, TEMPLATES, AND STATIC FILES

To get started, we’ll create a new directory to house our App. This can be placed / named anywhere / anything reasonable, but make sure not to name it with anything like ‘flask’ to avoid names clashing.

cd into this newly created directory and create a directory called FlaskTask, our App’s project root directory. This directory will contain all files needed to create FlaskTask.

Our application code is a python file, so we’ll need to create that now. This is simply a python file called ‘task.py’.

Templates

Over the years, web pages have been hard-coded by developers to return just what they put in, no dynamism. But recently, web contents can now be generated automatically by codes on the web servers and then served to the browsers as HTML pages before it is then displayed.

However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML.

This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hard-coded HTML from the function, a HTML file can be rendered by the render_template() function (we’ll see how this is used later). The render_template() function takes in an HTML template (in this case, it is simply a HTML code with some python expressions and statements based on the Jinja2 template system) which is then filled with values based on conditions stated in the template before it is now sent to the browser as a pure HTML code.

To do this, Flask searches for HTML templates in a special folder called ‘templates’, which should be placed directly inside our root project folder and next to our python file.

Static Files

Although Flask produces web Apps with dynamically generated contents, web Apps still need some static files such as necessary JavaScript files, CSS stylesheets, images, and so on. Normally, web servers are configured to serve your static files for you, but you’ll need to house them somewhere during development.

To keep our static files, Flask requires us to put them in a folder called ‘static’. For this we’ll create a directory called ‘static’, directly inside our root project and next to our python file.

3. URL ROUTING AND BUILDING

Our Python File

Open ‘task.py’ and add the following lines of code to it:

File ‘task.py’

That’s a very simple Flask app, probably the most basic. Let’s explain the code here:

  • We imported Flask class from the flask module we installed. This class will be the basic building block of our app — an instance of it is our WSGI application.
  • Next we create an instance of this class. The parameter given to it is the name of the application’s module or package. If you are using a single module (as in this example), you should use __name__ because depending on if it’s started as application or imported as module the name will be different ( __main__ versus the actual import name). This is needed so that Flask knows where to look for templates, static files, and so on. For more information have a look at the Flask documentation.
  • The next line sets ‘debug’ variable of the instance to True, to allow us see error messages in our browser during development. However, this shouldn’t be done when packaging the app for production! ‘debug’ should be set to False (by default, it is set to False).
  • We then use the route() decorator to tell Flask what URL should call the function binded to it.
  • The function is given a name which is also used to generate URLs for that particular function, and returns the message we want to display in the user’s browser.

Simply run this script in your terminal, you should see something like this if all goes on well:

Now, open your browser any navigate to ‘http://127.0.0.1:5000/home' to see the output.

Your browser should simply display:

This is the homepage!

That indicates that your installation and development server is up and running!

Now edit the ‘task.py’ file and make the following change:

File ‘task.py’

Go to your browser and re-load the page, you should get an error such as:

404 error! Page Not Found

Why did this happen?

This is because your browser takes in ‘/home’ address, and your python script couldn’t find any function binded to it. Try navigating to ‘http://127.0.0.1:5000/homey' and everything should work just fine now.

This shows the significance of URL routing to your web app. But we can also generate URLs dynamically. We can do this by adding variable parts to the route() decorator as parameters.

This variable part is marked as <variable-name>. It is then passed as a keyword argument to the function with which the rule is associated. To demonstrate this, let’s edit our Python code:

Open ‘http://127.0.0.1:5000/home/Trump' in your browser to see the output, which is something like:

Welcome to my home page Trump!

What did we do here?

We simply created a rule that can take in a variable name and pass it along to the function binded to it. This way, we can have different URLs that will return different contents based on the name passed to it! Try changing Trump in the URL to Obama, and the browser should return a corresponding page.

URL Building

The url_for() function is very useful for dynamically building a URL for a specific function. The function accepts the name of a function as first argument, and one or more keyword arguments, each corresponding to the variable part of URL. To use it, we need to import it from flask module.

The following script demonstrates use of url_for() function:

In the code above, we have avoided hard-coding URLs for different functions by using the url_for() function which returns the required URL for the function whose name is provided.

Also, we can build URLs for our static files present in the ‘static’ folder. Flask uses the folder ‘static’ as the first positional argument to the url_for() function, just like we’ll use the name of the function we want to build a URL for, and the name of the static file as a keyword argument to ‘filename’. Say we have a CSS stylesheet and an image in our ‘static’ folder. Building URLs for them, we use something like:

Now, to use them in our HTML page and Python code, we do the following:

This simplifies code editing, as you can change the name of your images or style sheets without worrying about changing them in your HTML code, and you’ve just avoided headaches you get when using absolute paths for your static files in HTML codes.

FlaskTask

Enough said, let’s start building FlaskTask. Remember the functions of the App? Save a task for the user, and display a list of the user’s saved tasks. For this, we’ll need three views — the home page with links to ‘Add a task’ and ‘View a task’, the view-task page that shows the tasks saved by the user, and the add-task page that gives the user text boxes to write the task and save them. We will talk about the HTTP methods needed in these HTML files in a moment.

Right now, make sure your project directory looks like this:

Now, let’s add our three HTML views. Open ‘templates’ folder and create three HTML files — homepage.html, addtask.html, and viewtask.html. We’ll also use a CSS stylesheet, open the ‘static’ folder and create a CSS file — styles.css. Your project directory should look like this now:

That should be all, for now at least.

4. HTTP METHODS AND REQUEST OBJECT

HTTP Methods

Http protocol is the foundation of data communication in world wide web. Different methods of data retrieval from specified URL are defined in this protocol. The HTTP method (also often called “the verb”) tells the server what the client wants to do with the requested page.The following list summarizes different http methods:

GET: The browser tells the server to just get the information stored on that page and send it. This is probably the most common method.

HEAD: The browser tells the server to get the information, but it is only interested in the headers, not the content of the page. An application is supposed to handle that as if a GET request was received but to not deliver the actual content. In Flask you don’t have to deal with that at all, the underlying Werkzeug library handles that for you.

POST: The browser tells the server that it wants to post some new information to that URL and that the server must ensure the data is stored and only stored once. This is how HTML forms usually transmit data to the server.

PUT: Similar to POST but the server might trigger the store procedure multiple times by overwriting the old values more than once. Now you might be asking why this is useful, but there are some good reasons to do it this way. Consider that the connection is lost during transmission: in this situation a system between the browser and the server might receive the request safely a second time without breaking things. With POST that would not be possible because it must only be triggered once.

DELETE: Remove the information at the given location.

OPTIONS: Provides a quick way for a client to figure out which methods are supported by this URL. Starting with Flask 0.6, this is implemented for you automatically.

By default, Flask route responds to the GET requests. However, this preference can be altered by providing ‘methods’ argument to route() decorator. An example is given below:

We’ll be using the ‘POST’ method frequently to post data from HTML form elements to our back-end for processing.

Request Object

The data submitted by the user from form elements are sent to the data as global request objects. In order to process them in our Python code, we need to import ‘request’ class from flask module. The request object contains some important attributes such as:

  • form: It is a dictionary object containing key-value pairs of form parameters and their values.
  • args: parsed contents of query string which is part of URL after question mark (?).
  • cookies: dictionary object holding Cookie names and values.
  • files: data pertaining to uploaded file.
  • method: current request method.

FlaskTask

Now let’s edit our ‘task.py’ file

File ‘task.py’

In the first line, we imported the classes we need for the App. Subsequently, we have used all the basics of Flask we discussed previously, the rest are just simple Python codes. Because FlaskTask is just a simple web app to explain some basics of Flask, we didn’t save our data using any database. Instead, we simply stored the data received from the request object as Python dictionary objects and read the values needed from there.

These are the HTML files:

File ‘homepage.html’

File ‘addtask.html’

File ‘viewtask.html’

--

--

Bello Mubarak
CodebagNG

Python 🐍 | Js Front-end web dev 😇💪💻 Computer engineering student at OAU **Bio link: https://about.me/mubarak-bello