Flask - Complete Tutorial

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.

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

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 app.run() function.

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.

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:

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:

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

Thank you so much, very helpful.