Get Started with Flask Python

4 min read

Table of Contents:

Title Image for the Article

Introduction

Creating a website can be a fun experience! However, some other frameworks can be quite heavy and just have too many tools for what you need. Let's take a look into the framework Flask that is fast and easy to use!

Don't have Python? Install it here!

To follow along with the tutorial you will need to have Python installed. If you are using Mac or Linux ensure that you are using "Python3" instead of "Python" (which defaults to V2).

Create a Virtual Enivornment

Python loves virtual environments to keep packages separate from each other to ensure you do not have conflicts with package names or version issues. Luckily, Python has a built-in module that handles Virtual Environments.

If you have Python installed on your machine, you will be able to use Virtual Environment because it is a default module.

Go to the folder where you want to setup your project and you will run:

python3 -m venv flasktest # <- for LINUX & MACOSX
py -m venv env flasktest # <- for Windows

Now Run:

source env/bin/activate # <- for LINUX & MACOSX
.envScriptsactivate # <- for Windows

Your terminal should change slightly (with a PREFIX) to the front of it!

This creates a unique environment to keep it encapsulated from the rest of the computer.

Do I need to save anything when I leave the environment?

Nope! There is no special saving you have to do in a virtual environment. The only thing that will be lost is environment which is not a huge deal.

Get Flask Up and Running

We simply have to run a command:

pip install Flask

Now that we have Flask installed we get it started!

In your folder create a file called "main.py" and write the following into it:

from flask import Flask, render_template
app = Flask(__name__)
@app.route("/", methods=['GET'])
def index():
    return render_template('index.html')
@app.route("/api")
def hello_api():
    return_api = {
        "name": "Old Greg",
        "Fast Food": "taco bell"
    }
    return return_api

Special note on the second line of code.

app = Flask(__name__)

This lets Flask know this file is the entry point of the application. While we have to tell Flask later on what the entry point is, this sets the application to this specific file.

Decorators

A decorator is a special function that wraps another function. In Flask we have the app.route decorator. This allows the app to call this function when someone goes to that specific route.

The two methods we made go for the "/" (the root or top level of the application) and "/api". We are going to use the API route to show how easy it is to implement an API request with Flask.

Create the Template

Create a folder called "templates" in the directory of your project. This is a special folder name that Flask will look for templates.

Templates are what we use to generate HTML for the user to see.

Inside the templates folder create a "base.html" and "index.html"

Base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <div class="container-fluid">
    <a class="navbar-brand" href="{{ url_for('index') }}">Navbar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav me-auto mb-2 mb-lg-0">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="{{ url_for('index') }}">Home</a>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Dropdown
          </a>
          <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
            <li><a class="dropdown-item" href="#">Action</a></li>
            <li><a class="dropdown-item" href="#">Another action</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" href="#">Something else here</a></li>
          </ul>
        </li>
        <li class="nav-item">
          <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
        </li>
      </ul>
      <form class="d-flex">
        <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
        <button class="btn btn-outline-success" type="submit">Search</button>
      </form>
    </div>
  </div>
</nav>
    <div>
        {% block content %}{% endblock %}
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
    <script src="{{ url_for('static', filename='app.js') }}"></script>
</body>
</html>

The base file seems like it has a lot in it!

It is using the boilerplate of Bootstrap CSS to create a foundation. The Base file is used to keep a foundation template so that our website keeps the same look.

index.html

{% extends "base.html" %}
{% block content %}
<button class="btn btn-success" onclick="fetch_response()">Click me!</button>
{% endblock %}

The index file is a lot smaller because it "extends" (or inherits) the look of the base file. Instead of rewriting code, we can create templates to keep things the same unless we need to change sections (such as the content block).

Static Folder

At the root of our application we will create another folder called static and inside of it create a file called "app.js"

app.js

const fetch_response = () =>
{
    fetch('/api')
    .then(response => response.json())
    .then(data => alert('The response was: ' + data['name']))
}

This will be a short bit of code to show a fetch request from the frontend.

Now go back your terminal and type in:

export FLASK_APP=main # LINUX AND MACOSX
set FLASK_APP=main # WINDOWS CMD

Now in the same terminal run:

flask run

The output you should get is:

(venv) YOUR MACHINE flasktest % flask run
 * Serving Flask app 'main.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)

Click on the link "http://127.0.0.1:5000" to open your served website.

The URl

This URL is for local development and does not expose your website to your network. It is accessible to your machine. UNLESS you expose the port yourself

Click the Button

Not a lot works on this started website, expect clicking the button!

When you click it you should get an alert that shows the data put in. Tada you just made your first Flask website!

Conclusion

Keep tinkering around with the basics of Flask.

Create your own templates, create different fetch calls, read the documentation!

Flask is a minimal framework that ships with a basic set of tools. The more things you want to add to Flask the more packages you need to add. You can create your own modules to use with Flask but I advise looking into what is already built and monitored by the community for things like Database Access, Authorization/Authentication, and encryption/hashing.

Recent Articles

Push Weight with Python

Create a simple terminal application that can let you know how much weight you need to put on the ba...

Validate Forms in TypeScript

Relying on HTML to validate your forms is just one step in ensuring visitors enter their information...

Automation with NodeJS

NodeJS can help you automate simple tasks. Being a web developer you can achieve the same goals as o...

Automation with Python

Python can take boring tasks away from you so you can continue to do other things. It is a scripting...

Speed With Cache in WordPress

Most WordPress sites use Apache as their server. Apache has a lot of tools built into it to speed up...

Social Media