Skip to content
Sign upLog in

Flask - Complete Tutorial

Profile icon

Flask Tutorial

Please note: this tutorial assumes you are somewhat decent at Python.

Part 1: Setup

In order to make a Flask application, we will need to import the Flask library, as well as any other functions we will be using.

from flask import Flask # Yes, a capital F in Flask.

Next thing we need to do is initialize an application. We can do this easily by using the following:

app = Flask(__name__) # You could also do Flask("any text here")

Now that we have an application created, we can create routes (pages), change the config, etc.

Before we continue, we need to actually run our Flask application.

To do this, we use the function.
Example: host = "", # or port = 8080, # make sure this is a non privileged port debug = True # this will allow us to easily fix problems and bugs )

Part 2: Routes

Now that we have a Flask application, we need to add some pages to it or it feels empty :C.

To do this, we use the @app.route() decorator.
You just need to specify a path.

@app.route("/") # def index(): # You could name this whatever you want. return "Welcome to the index."

Let's go through this.
a. We made a new route via the @app.route("/") decorator.
b. We then passed the decorator a function to run whenever someone visits our route.
c. We returned the string "Welcome to..." to the browser to be rendered.

Now, run your repl and you should see:

If it worked, great. If it didn't, check your code and try again :).

Part 3: Dynamic Routes

So, let's say you have an online game platform.
You would have want to manually make everyone a profile page.

Pretty sucky and time consuming?

Well, your in luck; thanks to dynamic routes.

An example of a dynamic route:

@app.route("/dynamic/<string:user>") def dynamic(user): return f"This is {user}'s profile. :)"

Pretty simple, huh?
You just add a /<type:variable> to the end of your route.
Then take in that variable in your function.


Part 4: Templates

Templates are a great thing, they allow you to have a actually logical file structure.

To use a template, your going to need to add an additional import.
from flask import Flask, render_template

Now, in your root directory, make a folder named templates.
Inside of that directory, make a file called index.html.

Place whatever HTML you want inside of the index file, then replace your index's return statement with:

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

Rerun your application and check your index.
It should render your HTML.

Think I should continue this tutorial? I'm tired as heck right now.

You are viewing a single comment. View All
Profile icon