Skip to content
← Back to Community
Flask Tutorial: Part 1, the basics
Profile icon
h
has Hacker Plan
AllAwesome497

So I saw that there was no (complete) flask tutorials here, so I'm going to start this series.


Now before we start, its assumed that you already know basic html, so if you don't know html I recommend that you learn it first. This part is only the basics of flask, its not intended for advanced users.

Step 1: Install flask

Now first of all, you need to add the package flask to your repl. To do so, use the repl package manager. If you are for some reason, not using repl, simply run sudo pip3 install flask (assuming you already have python installed).
To install flask on repl, open the package manager:
Open package manager
Then search for flask
Search for flask
Finaly, click on Flask and hit the +
Install flask
You should then see flask install.


Step 2: Setup

This is to initialize your flask app, without any web pages.

So to start off, you will need your app object, so you can get that with:

app = Flask( # Create a flask app __name__, template_folder='templates', # Name of html file folder static_folder='static' # Name of directory for static files )

Then, to start the app:

if __name__ == "__main__": # Makes sure this is the main process app.run( # Starts the site host='0.0.0.0', # EStablishes the host, required for repl to detect the site port=random.randint(2000, 9000) # Randomly select the port the machine hosts on. )

Now, once you run this, you should get a page saying "Not Found" or a 404 error


Step 3: Making your first page

So to add a page to your site, simply add @app.route('/(page-path)') and on the next line, a function that doesnt take any arguments. To return an output, you can either return a string, or make a more advanced output.
A basic output:

@app.route('/') # '/' for the default page def home(): return "Wow this is a basic output!"

But you can also render an html file/template:

def base_page(): return render_template( 'base.html', # Template file path, starting from the templates folder. )

In base.html:

<h1>Hello there!</h1>

Now, when you run the page it should say "Hello there!"


Step 4: Use variables

Now, it gets a bit more fun. What we are doing now, is adding variables to be used in the template.
To add a variable to be used by the template simply add var_name=variable and the template will be able to read variable by using {{ var_name }}

@app.route('/') # What happens when the user visits the site def base_page(): random_num = random.randint(1, 100000) # Sets the random number return render_template( 'base.html', # Template file path, starting from the templates folder. random_number=random_num # Sets the variable random_number in the template )

In templates/base.html:

<h1>The number is {{ random_number }}</h1>

A full example:

In main.py:

import random, string from flask import Flask, render_template app = Flask( # Create a flask app __name__, template_folder='templates', # Name of html file folder static_folder='static' # Name of directory for static files ) ok_chars = string.ascii_letters + string.digits @app.route('/') # What happens when the user visits the site def base_page(): random_num = random.randint(1, 100000) # Sets the random number return render_template( 'base.html', # Template file path, starting from the templates folder. random_number=random_num # Sets the variable random_number in the template ) @app.route('/2') def page_2(): rand_ammnt = random.randint(10, 100) random_str = ''.join(random.choice(ok_chars) for a in range(rand_ammnt)) return render_template('site_2.html', random_str=random_str) if __name__ == "__main__": # Makes sure this is the main process app.run( # Starts the site host='0.0.0.0', # EStablishes the host, required for repl to detect the site port=random.randint(2000, 9000) # Randomly select the port the machine hosts on. )

In static/base.css:

cb { background-color: rgb(63, 63, 63) } a { color: black; -webkit-appearance: button; -moz-appearance: button; appearance: button; } body { text-align: center; font-family: 'IBM Plex Sans', sans-serif; background-color: black; color: white; }

In templates/base.html:

<!doctype html> <head> <title>Flask Tutorial!</title> <script src="/static/base.js"></script> <link href="/static/base.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans&display=swap" rel="stylesheet"> </head> <body> <h1>Hello!</h1> <p> The random number is: <cb>{{ random_number }}</cb>! <!--Gets the random number from the python file--> </p> <a href="/2">Visit site 2</a> </body>

In templates/site_2.html:

<!doctype html> <head> <title>Flask Tutorial!</title> <script src="/static/base.js"></script> <link href="/static/base.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans&display=swap" rel="stylesheet"> </head> <body> <h1>Hello!</h1> <p> The random string is: <cb>{{ random_str }}</cb>! <!--Gets the random number from the python file--> </p> <a href="/">Go back</a> </body>

Base page
Page at /2

Voters
Profile icon
jeweled
Profile icon
Nastik987
Profile icon
fannywillems
Profile icon
ClumpyW
Profile icon
JackBoyd
Profile icon
KlebKlebsson
Profile icon
RGG3
Profile icon
SamKianifar
Profile icon
microsoftflappy
Profile icon
RamiroEscalant1
Comments
hotnewtop
Profile icon
programmeruser
port=random.randint(2000, 9000)

Why the random port?

Profile icon
powerbox1000

@programmeruser probably for fun

Profile icon
DerrickLukimin

Help I got this:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

Profile icon
Anonoymousgamer

@DerrickLukimin I got the same problem

Profile icon
MasterwuYT
Profile icon
Cooli

@DerrickLukimin Try Reloading

Profile icon
snake7584

@DerrickLukimin you probably did app.route('/') but you're supposed to do @app.route('/')

Profile icon
FaCe_crazykid05

how do i access the webpage from outside the frame they provided?

Profile icon
Cooli

@FaCe_crazykid05 In the top right corner click on the "open in a new tab" button and done!

Profile icon
CoderSmart

I got "Replit: Package operation failed."

Profile icon
MasterwuYT

it doesn't work at all

Profile icon
cesarlopez200

Cool intro to flask. I tried another tutorial and got lost. This helped make things click!

Profile icon
Josue_Alexander

I'd love to ping other endpoints, but it seems like I can only refresh the "/" index route

Profile icon
novachelly

No Flask package comes up.

Profile icon
sammykothe

@novachelly Make sure you're running a Python repl. It won't work for some reason if you use an HTML repl.

Profile icon
AllAwesome497

@sammykothe html repls just forward the html files to the user, they don't execute any code, and do not allow serverside code..

Profile icon
Cooli

@novachelly There is a Flask template

Profile icon
Highwayman

When is part 2 coming out?

Profile icon
AllAwesome497

@Highwayman good question- what do you want to see in the next one?
I have some ideas on what to do but none of them are good enough to have their own tutorial.

Profile icon
Highwayman

@AllAwesome497 oh. Uh. I was following because I don’t know flask so I couldn’t say lol. 🤷‍♂️ I thought you already had a plan for a second one at the time sorry, maybe just make a tutorial like "helpful flask tips" and add all those separate ideas you had that didn’t amount enough on their own to be tutorials?

Profile icon
AllAwesome497

@Highwayman i did have an idea but i forgot it lol.

Profile icon
Highwayman
Profile icon
Chaoyue123

@AllAwesome497
Hello if ur still up for it, maybe can teach how to navigate to a different webpage? Like from '/' to '/user' page

Profile icon
CallingTheShots

@Chaoyue123 thats ez just change the route to "/user"

Profile icon
kindred

the link on the html page that went to site 2

Profile icon
AllAwesome497

@kindred Huh. Fixed it. If you are using chrome, thats your problem (works fine in the other browsers i tested).

Profile icon
kindred

why is the link invisible

Profile icon
AllAwesome497

@kindred what link?

Profile icon
Giothecoder

You shared a repl along with your tutorial, but the repl is private - was that on purpose?

Profile icon
AllAwesome497

@Giothecoder oh ya lemme fix that

Profile icon
AllAwesome497

Should be fixed now

Profile icon
Giothecoder

@AllAwesome497 yup, it works now! :)