Learn to Code via Tutorials on Repl.it!

← Back to all posts
Flask Tutorial!
ruiwenge2 (538)

This tutorial will cover a lot about Flask and its functions. But first of all...

What is Flask?

Well, Flask is a micro web framework written in Python. It allows you to build web applications.

This tutorial will teach you the following:

  • Routing a function
  • Returning HTML code
  • Templating
  • Handling GET/POST requests
  • Redirecting
  • Sending a file

Now we know what Flask is, let's create a Python repl, and get started!

To use Flask, we have to import the Flask class and create an instance. Then we'll route and run a function, and run the application:

from flask import Flask

app = Flask("app",
  template_folder="templates", # name of folder containing html templates
  static_folder="static" # name of folder for static files
)

app.run(host="0.0.0.0", port=8080) # run the application

After you run the code (and wait for the packaging), you will see a page showing a page not found error (because we haven't added any pages yet).

To add a page, we will use the route decorator, and create a function that will return some HTML to the page.

@app.route("/")
def index():
  return "hello world"

When you run the code, you will see a page that says hello world. To add a page in a different path name, you can use @app.route("/PATHNAME"), then create the function.

You can also have variables to route the function by using the less/greater than signs:

@app.route("/<string>")
def index(string):
  return "hello world"

This will make it so that if you enter anything as the path name, it will return hello world. Remember to include the variable in the parameter! To use the variable in the function, we can simply just type the variable name:

@app.route("/<string>")
def index(string):
  return string

Now this code will make it so if you enter /python as the path name, it will return python, and if you enter /replit as the path name, it will return replit.

To have static files (such as CSS or JavaScript), create a folder called static, and files will be kept in that folder. The path name for the static files will be /static/FILENAME.

Templating

Now this part will get a bit more interesting. So instead of returning a string in the function, we can render an HTML template. To do this, create a folder called templates, and create a file called index.html. We will have to import the render_template function from Flask:

from flask import Flask, render_template

The following code will render an HTML template:

@app.route("/")
def index():
  return render_template("index.html")

In the index.html file we have:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <button>Click me!</button>
  </body>
</html>

When you run your code, you should see a button that says Click me!.

Variables

To use variables in your template, use curly brackets in the HTML code: {{VARIABLENAME}}. In the Python code, we will need to create the variable and inject it into the template. In the HTML we have:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1>I like {{favfood}}.</h1>
  </body>
</html>

And in the Python code we have:

@app.route("/")
def index():
  food = "pizza"
  return render_template("index.html", favfood=food)

You should see I like pizza when you run the code. You can add however many variables you would like, but be sure to add parameters containing the variables into the render_template function.

If/Else

Flask allows you to use if and else statements in your HTML template. To create if and else statements in the template, use this syntax:

{% if STATEMENT %}
<!-- insert html here -->
{% elif STATEMENT %}
<!-- insert html here -->
{% else %}
<!-- insert html here -->
{% endif %} <!-- ends the if/else statement -->

So let's create an if/else statement. In the Python code we have:

@app.route("/")
def index():
  num = 5
  return render_template("index.html", number=num)

In the index.html, we use the variable number in the if/else statement:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    {% if number == 10 %}
    <p>The number is 10.</p>
    {% elif number == 5 %}
    <p>The number is 5.</p>
    {% else %}
    <p>The number is neither 10 nor 5.</p>
    {% endif %}
  </body>
</html>

When you run this, you should see The number is 5..

For Loops

Flask also allows you to use for loops in HTML templates. This can save a lot of code. To create for loops, use this syntax like if/else:

{% for STATEMENT %}
<!-- insert html here -->
{% endfor %} <!-- ends the for loop -->

Let's try it. In the Python code we have:

@app.route("/")
def index():
  return render_template("index.html")

And in the HTML template we have:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    {% for i in range(10) %}
    {{i}} <!-- shows the number "i" -->
    {% endfor %}
  </body>
</html>

The page should now show 0 1 2 3 4 5 6 7 8 9.

You can also use lists in a for loop. To do this, first create the list in the Python code:

@app.route("/")
def index():
  foods = ["pizza", "burger", "hot dog"]
  return render_template("index.html", foods=foods)

In index.html we have:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    {% for food in foods %} <!-- use the "foods" list -->
    <p>{{food}} is a food</p>
    {% endfor %}
  </body>
</html>

You should get this when you run it:

pizza is a food
burger is a food
hot dog is a food

Handling GET/POST requests

To recieve GET/POST requests, we will need to import request from Flask, and in the route decorator, we'll have to add the methods:

from flask import Flask, render_template, request

app = Flask("app")

@app.route("/", methods=["GET", "POST"])
def index():
  if request.method == "GET": # if form method is GET
    text = request.args["text"]
    return text
  elif request.method == "POST": # if form method is POST
    text = request.form["text"]
    return text
  return render_template("index.html") # if form is not submitted show the form

app.run(host="0.0.0.0", port=8080)

In index.html:

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

Once you enter a value in the input, you should see the text you entered. You can also change the form method to POST.

Redirecting

Redirecting is easy with Flask. Just import the redirect function and use it:

from flask import Flask, render_template, request, redirect

app = Flask("app")

@app.route("/")
def index():
  return redirect("URL")

app.run(host="0.0.0.0", port=8080)

So if you wanted to redirect to the Replit website, you would do:

def index():
  return redirect("https://replit.com")

Sending Files

Sending files is also easy with Flask. You will need to import send_file from Flask:

from flask import Flask, render_template, request, redirect, send_file

app = Flask("app")

@app.route("/")
def index():
  return send_file("image.png")

app.run(host="0.0.0.0", port=8080)

So you would need to have a file called image.png. The output would show the image file. If you send files, you must have access to them.

That's the end of this tutorial, and I hope you liked it and found it helpful!

Comments
hotnewtop
VulcanWM (2756)

i just dont get how send files work @ruiwenge2

ruiwenge2 (538)

@VulcanWM for example you uploaded a file called file.png in the main directory. then you'll have to import send_file from Flask, and the file that you use will be file.png

see here:

VulcanWM (2756)

oh makes sense, thanks! @ruiwenge2

ruiwenge2 (538)

the cool thing is you can use the img tag to embed that image, like <img src="https://illfatedunfitpercent.ruiwenge2.repl.co">
@VulcanWM

VulcanWM (2756)

thank you! this just helped me in something i was trying to do right now! @ruiwenge2

ruiwenge2 (538)

i'm just curious, what were you trying to do? @VulcanWM

ruiwenge2 (538)

oh! i think it was the pfp @VulcanWM

VulcanWM (2756)

Yep the way you actually went on the repl to see the code @ruiwenge2

Yoplayer1py (5)

@ruiwenge2 What will send_file do ?

VulcanWM (2756)

It will send an image file or something to the person opening the website. An example is here: https://replit.com/@VulcanWM/OvalEyes
The output will be shown here: https://ovaleyes.vulcanwm.repl.co/pfps/vulcanwm @Yoplayer1py

VulcanWM (2756)

i see you're on the website lmfao @ruiwenge2

ruiwenge2 (538)

@VulcanWM OvalEyes is a creative name

VulcanWM (2756)

ty (i only made it that bc i have oval eyes) @ruiwenge2

JakeHu2020 (20)

Nice, I needed to see one of these so badly. Thanks!

CosmicBear (6)

jinja described as "curly brackets and percent signs".

ruiwenge2 (538)

@CosmicBear i changed it though lol

CosmicBear (6)

@ruiwenge2 It is a good description though

CosmicBear (6)

of how to use it

CosmicBear (6)

@ruiwenge2 i didn't know about send_file

EpicGamer007 (1751)

wow, this is pretty nice. very concise, i learned a lot. :)