Skip to content
← Back to Community
Flask Tutorial!
Profile icon
ruiwenge2

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("/") def index(): return render_template("index.html") @app.route("/submit", methods=["GET", "POST"]) def submit(): 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 app.run(host="0.0.0.0", port=8080)

In index.html:

<form action="/submit" 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!

Voters
Profile icon
FIONAFENG2
Profile icon
RyanKeeler
Profile icon
ZachTaliaferro2
Profile icon
julianbrooks
Profile icon
simonknowsstuff
Profile icon
ruiwenge2
Profile icon
lukVn
Profile icon
so1oro1o
Profile icon
EkamSingh
Profile icon
motraor3
Comments
hotnewtop
Profile icon
codingjlu

Alright THIS IS A GOOD TUTORIAL THAT DESERVES an upvote (or two) :)

Profile icon
ruiwenge2
Profile icon
VulcanWM

Woah nice!

Profile icon
ruiwenge2
Profile icon
VulcanWM

i just dont get how send files work @ruiwenge2

Profile icon
ruiwenge2

@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:

Screen Shot 2021-06-10 at 8.42.06 AM

Profile icon
VulcanWM

oh makes sense, thanks! @ruiwenge2

Profile icon
ruiwenge2
Profile icon
ruiwenge2

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

Profile icon
VulcanWM
Profile icon
VulcanWM

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

Profile icon
ruiwenge2

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

Profile icon
ruiwenge2

oh! i think it was the pfp @VulcanWM

Profile icon
VulcanWM

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

Profile icon
ruiwenge2
Profile icon
Yoplayer1py

@ruiwenge2 What will send_file do ?

Profile icon
VulcanWM

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

Profile icon
VulcanWM

i see you're on the website lmfao @ruiwenge2

Profile icon
ruiwenge2

@VulcanWM OvalEyes is a creative name

Profile icon
VulcanWM

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

Profile icon
ruiwenge2
Profile icon
shoplectic

This command is really useful, i used too to use it in coding. thanks for sharing... https://www.shoplectic.com/product/halftime-tracksuit/

image

Profile icon
lisawilliams1

Morbius Loxias Crown Grey Coat is upcoming on trending and everyone wants to get this product and we know this product is being sold on various platform but we are providing genuine quality with free shipping
"
https://theleatherz.com/product/morbius-loxias-crown-trench-coat/

Profile icon
PeterMoss

Flask is a good choice if you want to create a basic and lightweight web application. Although it is not as strong and broad as Django, it does provide capabilities like as support for unit testing and the creation of REST APIs. https://domyonlineexam.com/online-course-help.php

Profile icon
Willie7488

Thanks for sharing this info this is useful keep it up.
https://www.myccpay.today/

Profile icon
Sanchez25

Flask is one of the easiest microframework to learn in Python. If you wish to develop a simple and lightweight web application then Flask is suitable for that. It is not as powerful and extensive as Django still provides features such as support for unit testing and building REST APIs.

https://www.advancedmd.online/

Profile icon
CodingElf66

Really nicely written tutorial, I'm reading it right now and I have a clear view of Flask, thank you @ruiwenge2! Tysm! This surely needs more upvotes to match your hard work and everything! Here's an upvote!!!

Profile icon
ruiwenge2
Profile icon
Loshad

good

Profile icon
JWZ6

so cool :)

Profile icon
ruiwenge2

@JWZ6 thanks

Profile icon
JWZ6
Profile icon
ruiwenge2

@JWZ6 its my birthday today :)
and i made a multiplayer pong game. do you want to play against me?
https://replit.com/talk/share/MultiPong-A-multiplayer-pong-game-and-its-my-birthday-today-D/143432

Profile icon
JWZ6
Profile icon
ruiwenge2
Profile icon
A036Nikhil

can you please create a tutorial on Creating Login form using flask and replit database?

Profile icon
ruiwenge2
Profile icon
QuantumCodes

Wow! The best tutorial I've seen till now! Thanks for making this! For the get or post method, html gives data to py? Can we also send data from py to html?

Profile icon
ruiwenge2

@QuantumCodes you can receive data in html with a get request, but not post

Profile icon
QuantumCodes

@ruiwenge2

request.form[]

Gets from post??

Profile icon
ruiwenge2
Profile icon
JWZ6

pogger

Profile icon
ruiwenge2

thanks @JWZ6

Profile icon
JWZ6

@ruiwenge2 like srsly dude

Profile icon
ruiwenge2

@JWZ6 what?

Profile icon
JWZ6

@ruiwenge2 is good

Profile icon
ruiwenge2

@JWZ6 yay!

Profile icon
JWZ6

@ruiwenge2 dis deserves more updoots

Profile icon
ruiwenge2

well
its only been several hours
@JWZ6

Profile icon
JWZ6
Profile icon
JakeHu2020

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

Profile icon
ruiwenge2
Profile icon
CosmicBear

jinja described as "curly brackets and percent signs".

Profile icon
CosmicBear

Chit CHat

Profile icon
ruiwenge2

@CosmicBear i changed it though lol

Profile icon
CosmicBear

@ruiwenge2 It is a good description though

Profile icon
CosmicBear

of how to use it

Profile icon
ruiwenge2

@CosmicBear thanks!

Profile icon
CosmicBear

@ruiwenge2 i didn't know about send_file

Profile icon
ruiwenge2

@CosmicBear now you know!

Profile icon
EpicGamer007

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

Profile icon
ruiwenge2