Flask Tutorial!
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!
Woah nice!
i just dont get how send files work @ruiwenge2
oh makes sense, thanks! @ruiwenge2
yeah @ruiwenge2
thank you! this just helped me in something i was trying to do right now! @ruiwenge2
Yep the way you actually went on the repl to see the code @ruiwenge2
@ruiwenge2 What will send_file do ?
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
i see you're on the website lmfao @ruiwenge2
ty (i only made it that bc i have oval eyes) @ruiwenge2
This command is really useful, i used too to use it in coding. thanks for sharing... https://www.shoplectic.com/product/halftime-tracksuit/
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/
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
Thanks for sharing this info this is useful keep it up.
https://www.myccpay.today/
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.
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!!!
@JeffreyChen13 thanks!!
good
so cool :)
@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
@ruiwenge2 sure
@JWZ6 can you give me feedback on my socket.io tutorial? https://replit.com/talk/learn/SocketIO-Tutorial-What-its-for-and-how-to-use/143781
can you please create a tutorial on Creating Login form using flask and replit database?
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?
@QuantumCodes you can receive data in html with a get request, but not post
pogger
@ruiwenge2 like srsly dude
@ruiwenge2 is good
@ruiwenge2 dis deserves more updoots
@ruiwenge2 still
Nice, I needed to see one of these so badly. Thanks!
jinja described as "curly brackets and percent signs".
Chit CHat
@CosmicBear i changed it though lol
@ruiwenge2 It is a good description though
of how to use it
@CosmicBear thanks!
@ruiwenge2 i didn't know about send_file
@CosmicBear now you know!
wow, this is pretty nice. very concise, i learned a lot. :)
Alright THIS IS A GOOD TUTORIAL THAT DESERVES an upvote (or two) :)
@codingjlu tysm!