Getting Started with Flask: Installation, Routes, Templates & More

This tutorial walks you through installing Flask, creating a simple "Hello Flask" app, enabling debug mode, defining routes and path variables, building URLs, handling HTTP methods, static files, templates, logging, request data, file uploads, cookies, redirects, responses, and sessions, providing clear code examples for each feature.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Getting Started with Flask: Installation, Routes, Templates & More

Installation

Install Flask using pip install flask. Then create a Python file with the following code and run it; visiting http://localhost:5000 will display Hello Flask!:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello Flask!'

if __name__ == '__main__':
    app.run()

Quick Start

Debug Mode

Enable Flask's built‑in debugger by setting the FLASK_DEBUG environment variable to 1. The server will automatically reload on code changes and display debugging information.

Routing

Routes are defined with the @app.route decorator, similar to Java annotations. Example:

@app.route('/')
def index():
    return 'Index Page'

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

Path Variables

Dynamic URL segments use the syntax /path/<converter:varname>. Common converters:

string : default, matches any text except a slash

int : matches integers

float : matches floating‑point numbers

path : like string but allows slashes

any : matches any of the given strings

uuid : matches a UUID string

Example from the Flask docs:

@app.route('/user/<username>')
def show_user_profile(username):
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post %d' % post_id

URL Building

Generate URLs with url_for('function_name'):

from flask import Flask, url_for
app = Flask(__name__)

@app.route('/')
def index():
    pass

@app.route('/login')
def login():
    pass

@app.route('/user/<username>')
def profile(username):
    pass

with app.test_request_context():
    print(url_for('index'))          # /
    print(url_for('login'))          # /login
    print(url_for('login', next='/'))
    print(url_for('profile', username='John Doe'))

HTTP Methods

Specify allowed methods in the route decorator:

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # process login
        pass
    else:
        # show login form
        pass

Static Files

Serve static assets using url_for('static', filename='style.css') and place the files in a static/ directory.

Template Rendering

Flask uses Jinja2 for templating. Render a template with render_template('hello.html', name=name):

from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)

Example hello.html:

<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

Logging

Flask provides a pre‑configured logger accessible via app.logger:

app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')

Request Handling

Request Object

Access query parameters with request.args, form data with request.form, and uploaded files with request.files:

from flask import request

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        # validate login
        pass
    else:
        # show login form
        pass
    return render_template('login.html')

searchword = request.args.get('key', '')

File Upload

Save uploaded files securely using werkzeug.utils.secure_filename:

from flask import request
from werkzeug.utils import secure_filename

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/' + secure_filename(f.filename))

Cookies

Read a cookie with request.cookies.get('username') and set one with make_response:

from flask import request, make_response, render_template

@app.route('/')
def index():
    username = request.cookies.get('username')
    # use username
    resp = make_response(render_template('index.html'))
    resp.set_cookie('username', 'the username')
    return resp

Redirects and Errors

Redirect with redirect(url_for('login')) and abort with abort(401). Custom error pages can be defined with @app.errorhandler:

from flask import abort, redirect, url_for, render_template

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

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

@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

Response Handling

Return strings, response objects, or use make_response to customize headers:

@app.errorhandler(404)
def not_found(error):
    resp = make_response(render_template('error.html'), 404)
    resp.headers['X-Something'] = 'A value'
    return resp

Sessions

Manage user sessions via the session object, which stores data in signed cookies:

from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

@app.route('/')
def index():
    if 'username' in session:
        return 'Logged in as %s' % escape(session['username'])
    return 'You are not logged in'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        session['username'] = request.form['username']
        return redirect(url_for('index'))
    return '''<form method="post"><p><input type=text name=username><p><input type=submit value=Login></form>'''

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('index'))

Template Basics

Jinja2 syntax uses {% %} for statements and {{ }} for expressions. Templates can extend a base layout, define blocks, and include control flow such as if statements and for loops.

{% extends 'layout.html' %}
{% block title %}Home{% endblock %}
{% block body %}
  <div class="jumbotron">
    <h1>Home</h1>
    <p>This project demonstrates basic Flask usage.</p>
  </div>
{% endblock %}

Loop example:

{% for key, value in data.items() %}
  <tr><td>{{ key }}</td><td>{{ value }}</td></tr>
{% endfor %}

Conditional example:

{% if not session.logged_in %}
  <a href="{{ url_for('login') }}">log in</a>
{% else %}
  <a href="{{ url_for('logout') }}">log out</a>
{% endif %}

This article provides a concise introduction to Flask's core features, enabling you to build a simple web service with Python.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPythonTutorial
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.