Learn to Code via Tutorials on Repl.it!

← Back to all posts
Flask Tutorial
SushiPython (54)

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

Comments
hotnewtop
isaiah08 (87)

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

CodingGoose (698)

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.

SushiPython (54)

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