Flask Python Tutorial – Complete Guide

In the exciting realm of web development, finding the right tool to get the job done can make all the difference. This article aims to introduce you to such a tool that has swept the Python community by storm in recent years, due to its simplicity and flexibility — Flask!

What is Flask?

Flask is a lightweight, yet powerful web framework written in Python. It is considered as a microframework meaning it has no specific tools or libraries. Flask encourages simplicity and minimalism, providing only the bare essentials to get you started with web development, making it a perfect tool for beginners.

What is Flask used for?

The versatility of Flask cannot be overstated. It’s used for a wide range of projects, everything from small scale personal blogs to large, complex web applications. With Flask, you essentially have the power to create just about any web application you can think of.

Why should I learn Flask?

Flask is written in Python, one of the most approachable and widely-used languages out there. For coding beginners, Flask offers a gentle introduction to the complex world of web development. If you’re already an experienced coder, Flask’s minimalist approach can help you get your web projects off the ground quickly. With Flask in your coding toolkit, you’ll be a highly valuable asset in the workplace.

Up next, we’re going through some practical exercises to help you start coding with Flask. Let’s dive straight in!

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Getting Started with Flask

To kick things off, you need to install Flask. Make sure you have Python installed on your machine and let’s write in Terminal or Command Prompt:

pip install flask

Now, let’s move into writing some basic code. Below is how you create a simple application in Flask:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return 'Hello, World!'

This simple application will return “Hello, World!” when you access the root URL of the local server.

Building Routes in Flask

In Flask, you use the route() decorator to bind a function to a URL. Let’s create another route:

@app.route('/about')
def about():
    return 'About Page'

Now, if you go to the ‘/about’ URL, you’ll see the text ‘About Page’.

Using Templates in Flask

Flask allows you to render templates for better front-end design. To use templates, you need to create a templates folder and put your HTML files there:

from flask import render_template

@app.route('/welcome')
def welcome():
    return render_template('welcome.html')

This code will render the ‘welcome.html’ file when you access the ‘/welcome’ URL.

Working With Variables in Flask

Flask also allows you to pass variables from your Python code to your HTML templates:

@app.route('/user/')
def user(username):
    return render_template('user.html', name=username)

On the ‘user.html’ page, you can use the variable ‘name’ to print the username passed in the URL.

Handling HTTP Methods in Flask

Flask routes default to handling GET requests. However, they can also be set to handle other HTTP methods by providing a list of methods to the route():

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

This route will respond differently depending if a GET or a POST request is made.

Redirects and Errors

In Flask, you can easily redirect users and handle errors using the redirect() and abort() functions:

from flask import abort, redirect, url_for

@app.route('/')
def index():
    return redirect(url_for('login'))

@app.route('/login')
def login():
    abort(401)
    this_is_never_executed()

In this example, the root URL redirects to the login page, which immediately returns a 401 error.

Serving Static Files

To serve static files such as images or CSS files, use the special ‘static’ route and the url_for() function:

@app.route('/')
def index():
    return '<img src="'+ url_for('static', filename='logo.png') +'" alt="logo" />'

This code serves the ‘logo.png’ file located in the static directory.

Sessions in Flask

A session allows you to remember information from one request to another. In Flask, session is a dictionary object that you can use to store values:

from flask import Flask, session, redirect, url_for, escape, request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    
@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('index'))

Here, during login, a new session is started by adding a username to the session object. During logout, the session is cleared by removing the username from the session object.

How to Keep Learning

Learning is a constant journey, especially in the fast-paced world of coding and web development. There’s always more to explore, more challenges to tackle, and new tools to master. That’s why it’s essential to find a learning path tailored to your needs, one that will support your growth every step of the way.

A great place to continue your learning path is our comprehensive Python Mini-Degree. This program extensively covers Python programming, a popular language known for its simple syntax and versatility.

From coding basics to the intricacies of game development and app creation, this mini-degree has content that caters to beginners and experienced learners alike. The curriculum is designed to provide interactive lessons, coding challenges, and quizzes to reinforce your learning.

For those who have passed the basics and are looking to dive deeper into Python, we highly recommend checking out our collection of Python courses.

Whether you are taking your first steps into the world of Python or building upon existing knowledge, our courses are designed to fit into any schedule and paced to aid in understanding and application of the principles taught.

Remember, the key to learning is consistency. By regularly engaging with our courses and continually challenging yourself with new projects and concepts, you’ll be on your way to becoming a Python expert in no time. Let us at Zenva be part of your journey to becoming a coding professional. Happy coding!

Conclusion

Navigating the world of web development can seem like a daunting task, but with the right tools and a clear path, you’ll quickly achieve your objectives. Learning Flask is an excellent starting point for your Python-filled journey, offering a balance between simplicity and power.

Remember, the first step is often the hardest, but once you start seeing your creativity come to life through code, you’ll be hooked. At Zenva, we’re thrilled to be part of your incredible learning journey. Our Python Mini-Degree is designed to build foundational skills and encourage deeper exploration. So what are you waiting for? Dive in and start creating!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.