Flask Tutorial

Flask Tutorial

Note, this is Python Only

Flask is a micro web framework written in Python. It is classified as a microframework because it does not require particular tools or libraries. However, Flask supports extensions that can add application features as if they were implemented in Flask itself.

In this tutorial, we are going to be covering 6 things:

  • A Minimal Flask App
  • A Redirect
  • Rendering HTML Templates
  • Getting Variables from URLs
  • Passing Variables to HTML through Jinja2
  • Handling GET and POST requests
  • Bonus: Serving Static Files

Minimal Flask App

A flask application has 5 components:

  • Import the Flask Class
  • Create an Instance of the Flask Class
  • Route the function
  • Run the function
  • Run the application

A simple flask application can be written in only 6 lines of code, but I will make it longer for readability.

This code should return

Hello World

You have successfully created, initialized, and ran a Flask application.

Flask Redirect

To redirect, we need to do 2 things:

  • Import redirect from Flask
  • Call upon the redirect with a status code

This code should redirect to https://sushipython.us
You have successfully ran a flask redirect.

Rendering HTML Templates

To render HTML files, or templates, we need to do 3 things:

  • Import render_template from Flask
  • Create an HTML template
  • Call upon the render_template

Before we start coding, put HTML Markup in a file located at /templates/index.html

(in main.py)

This code should run your HTML File.
You have successfully rendered an HTML template in Flask.

Getting Variables from URLs

To get variables from the URL, you need to do 2 things:

  • Assign the variable to an argument in the function
  • Detect the variable in the URL

At /example, it should return


You have successfully gotten a variable from the URL!

Passing Variables to HTML via Jinja2

To Pass Variables to HTML, you must do 2 things:

  • Create an HTML template
  • Tell Flask to send the variables to the template

Note: Referencing Variables With Jinja2 Looks like: {{var}}

(in main.py)

(in index.html)

This should print

Your var is string

Handling Get and Post Requests

To handle get and post requests, you must do 4 things:

  • Import request from flask
  • Allow Post Methods
  • Identify the request method
  • Gather the Post Request

(in index.html)

Try inputting data to the form, and see what happens!

Bonus: Serving Static Files

Many people have trouble serving static files in Flask, but it is easy. Create a directory /static/ and put all your files in there. To activate this static folder, create an instance with:

Thank you for reading this, and I hope you learned something.
This is my first Repl Talk post, so if you have feedback let me know.


You are viewing a single comment. View All

@DannyIsCoding I'd recommend Flask because of it's simplicity, but really it's up to you.