Skip to content
← Back to Community
Flask Tutorial
Profile icon
SushiPython

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.

from flask import Flask # Import Flask Class app = Flask(__name__) # Create an Instance @app.route('/') # Route the Function def main(): # Run the function return 'Hello World' app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)

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
from flask import Flask, redirect # Import Flask Class, and redirect app = Flask(__name__) # Create an Instance @app.route('/') # Route the Function def main(): # Run the function return redirect('https://sushipython.us', 302) # Call upon the redirect with status code 302 app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)

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)

from flask import Flask, render_template # Import Flask Class, and render_template app = Flask(__name__) # Create an Instance @app.route('/') # Route the Function def main(): # Run the function return render_template('index.html') # Render the template app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)

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
from flask import Flask # Import Flask Class app = Flask(__name__) # Create an Instance @app.route('/<var>') # Route the Function def main(var): # Run the function with an arg 'var' return var # Returns var app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)

At /example, it should return

example

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)

from flask import Flask # Import Flask Class app = Flask(__name__) # Create an Instance @app.route('/') # Route the Function def main(): # Run the function x = 'String' # Set x to 'String' return render_template('index.html', x=x) # Render the template with a variable app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)

(in index.html)

<h1>Some Text</h1> <p>Your var is {{x}}</p>

This should print

SOME TEXT
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
from flask import Flask, render_template, request # Import Flask and RenderTemplate and Request app = Flask(__name__) # Create an Instance @app.route('/', methods=['GET', 'POST']) # Route the Function and allow Requests def main(): # Run the function if request.method == 'POST': # Identify Request Method value = request.form['input'] # Gather the Post Request return value if request.method == 'GET': # Identify Request Method return render_template('index.html') app.run(host='0.0.0.0', port=5000, debug=True) # Run the Application (in debug mode)

(in index.html)

<form method="POST" action=""> <input type="text" name="input"> <input type="submit"> </form>

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:

app = Flask(__name__, static_url_path='/static')

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.

Sushi

Voters
Profile icon
nandanmhatre
Profile icon
MatthewSchmeeck
Profile icon
Jasonplatanos
Profile icon
DanielKrusinski
Profile icon
evhunter09
Profile icon
OG49
Profile icon
OpenSourced
Profile icon
bekishore
Profile icon
lukVn
Profile icon
PotatoWatch
Comments
hotnewtop
Profile icon
isaiah08

Thank you SO much for this, I spent over an hour googling how to use flask!

Profile icon
SushiPython

@isaiah08 No problem!

Profile icon
JayCuthrell

This is a comment to thank you for adding comments in your examples. 🤓

Profile icon
AruSarda

kj

Profile icon
Gomenburu

for the Flask Redirect i am using pycharm, and i get the This site can’t be reached page, even though i just copied and pasted the code, just changing the thing it gets redirected to. can anyone help?
Screenshot 2022-02-22 19.26.20

Profile icon
DanielKrusinski

Man, thanks! I have been searching it for 3 hours!

Profile icon
CodingGoose

Is Flask or Django better? I want to start with python web development and I don't know which to start learning.

Great tutorial btw.

Profile icon
SushiPython

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

Profile icon
CodingGoose

@SushiPython Ok, thanks!

Profile icon
Codemonkey51

Cool