Lesson 65 of 70 – Python Flask
93%

Python Flask

Flask is a lightweight Python web framework used to build web applications, websites and APIs. It provides the basic tools needed to handle web requests and create dynamic web applications.

Note: Flask is designed to be simple and flexible. Additional functionality can be added through extensions and other Python packages.
What is Flask?

Flask is a Python web framework that helps developers create web applications and APIs.

A Flask application can receive a request from a browser, execute Python code and return a response.

Browser
   |
   | HTTP Request
   ↓
Flask Application
   |
   | Python Code
   ↓
HTTP Response
   |
   ↓
Browser
Why Use Flask?
  • Build web applications
  • Create REST APIs
  • Build backend services
  • Connect applications with databases
  • Handle HTTP requests
  • Render HTML templates
  • Create small and medium-sized web applications
  • Build prototypes quickly
Installing Flask

Flask can be installed using pip.

pip install flask

You can also use:

python -m pip install flask
Creating Your First Flask Application

Create a Python file named app.py.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello, Flask!"

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

Run the program:

python app.py

The development server will start and provide a local address that you can open in a browser.

Importing Flask
from flask import Flask

The Flask class is imported from the Flask package.

The application object is then created:

app = Flask(__name__)

This object represents the Flask application.

What is a Route?

A route connects a URL path to a Python function.

@app.route("/")
def home():
    return "Welcome to my website"

When a browser requests the root URL, Flask calls the home() function.

Creating Multiple Routes

A Flask application can contain multiple routes.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Home Page"

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

@app.route("/contact")
def contact():
    return "Contact Page"

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

Each URL is connected to a different Python function.

Running Flask in Debug Mode

Debug mode provides useful development features such as automatic reloading and detailed error information.

app.run(debug=True)
Important: Debug mode is intended for development. Do not enable the interactive debugger on a production server exposed to untrusted users.
Returning HTML

A Flask route can return HTML content.

@app.route("/")
def home():

    return """
    <h1>Welcome to Flask</h1>
    <p>This is my first Flask application.</p>
    """
Using HTML Templates

For larger web pages, Flask commonly uses the Jinja template engine. HTML templates are normally stored inside a folder named templates.

Example project structure:

project/
│
├── app.py
│
└── templates/
    └── home.html
render_template()

The render_template() function is used to render an HTML template.

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
    return render_template("home.html")
Passing Data to Templates

Python values can be passed to a template.

@app.route("/")
def home():

    name = "Rahul"

    return render_template(
        "home.html",
        student=name
    )

Inside home.html:

<h1>Welcome {{ student }}</h1>
Jinja Variables

Jinja uses double curly braces to display variables.

<h1>{{ name }}</h1>

<p>Course: {{ course }}</p>

Flask passes the values from Python to the template.

Jinja if Statement

Jinja templates can contain conditional logic.

{% if age >= 18 %}

    <p>You are an adult.</p>

{% else %}

    <p>You are a minor.</p>

{% endif %}
Jinja for Loop

A Jinja for loop can display items from a Python list.

{% for student in students %}

    <p>{{ student }}</p>

{% endfor %}

The students list can be supplied by the Flask application.

URL Parameters

Dynamic URL parameters can be defined inside a route.

@app.route("/user/<name>")
def user(name):

    return "Hello " + name

For example:

/user/Rahul

The value Rahul is passed to the name parameter.

URL Converter

Flask supports converters that allow route parameters to be interpreted as particular types.

@app.route("/student/<int:id>")
def student(id):

    return f"Student ID: {id}"

The int converter expects the URL value to be an integer.

HTTP Methods

A route can specify which HTTP methods it accepts.

from flask import Flask, request

app = Flask(__name__)

@app.route("/login", methods=["GET", "POST"])
def login():

    if request.method == "POST":
        return "Login submitted"

    return "Login form"
Reading Form Data

The request.form object can be used to access submitted form data.

from flask import Flask, request

app = Flask(__name__)

@app.route("/login", methods=["POST"])
def login():

    username = request.form.get("username")

    return "Welcome " + username

Using get() is useful because it returns None when the key is not present instead of raising a key error.

Reading Query Parameters

Query parameters can be accessed through request.args.

from flask import Flask, request

app = Flask(__name__)

@app.route("/search")
def search():

    keyword = request.args.get("q")

    return "Search: " + str(keyword)

A URL such as:

/search?q=python

provides python as the value of q.

Returning JSON

Flask can return JSON data from a route.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api/student")
def student():

    data = {
        "id": 1,
        "name": "Rahul",
        "course": "Python"
    }

    return jsonify(data)
Flask REST API

Flask can be used to build REST-style APIs.

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api/students")
def students():

    data = [
        {
            "id": 1,
            "name": "Rahul"
        },
        {
            "id": 2,
            "name": "Priya"
        }
    ]

    return jsonify(data)

if __name__ == "__main__":
    app.run()
Redirecting Users

The redirect() function can redirect a user to another URL.

from flask import Flask, redirect

app = Flask(__name__)

@app.route("/old")
def old_page():

    return redirect("/new")

@app.route("/new")
def new_page():

    return "New Page"
url_for()

The url_for() function generates a URL for a Flask endpoint.

from flask import Flask, url_for

app = Flask(__name__)

@app.route("/")
def home():

    print(url_for("about"))

    return "Home"

@app.route("/about")
def about():

    return "About"

Using endpoint names makes URL generation easier to maintain.

Static Files

CSS, JavaScript and image files are commonly stored in a static directory.

project/
│
├── app.py
│
├── static/
│   ├── style.css
│   └── script.js
│
└── templates/
    └── home.html

A template can reference a static file using url_for().

<link rel="stylesheet"
      href="{{ url_for('static', filename='style.css') }}">
Flask and Databases

Flask applications can connect to databases such as SQLite, MySQL and PostgreSQL.

A typical application may use Flask for the web layer and a database for storing application data.

Browser
   ↓
Flask
   ↓
Python Code
   ↓
Database
   ↓
Flask
   ↓
Browser
Project Structure

A simple Flask project can be organized like this:

myproject/
│
├── app.py
│
├── templates/
│   ├── home.html
│   ├── about.html
│   └── login.html
│
└── static/
    ├── css/
    │   └── style.css
    ├── js/
    │   └── script.js
    └── images/
Flask Application Factory Concept

For larger applications, it is common to create the Flask application inside a function rather than creating it directly at module level.

from flask import Flask

def create_app():

    app = Flask(__name__)

    @app.route("/")
    def home():
        return "Hello Flask"

    return app

This approach can make larger projects easier to configure and test.

Flask and Python Full Stack Development

Flask can be used as the backend of a full-stack application.

Frontend
HTML + CSS + JavaScript
        ↓
Flask Backend
        ↓
Python
        ↓
MySQL / SQLite
        ↓
Data

Flask can provide APIs or render HTML pages while the database stores application information.

Common Flask Mistakes
  • Forgetting to install Flask.
  • Using the wrong route URL.
  • Forgetting to import a required Flask function.
  • Using the wrong HTTP method.
  • Not validating form input.
  • Exposing sensitive information in source code.
  • Running the development debugger in an unsafe production environment.
  • Using incorrect template or static-file paths.
  • Not handling errors properly.
Complete Flask Example
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():

    name = "Rahul"

    return render_template(
        "home.html",
        student=name
    )

@app.route("/about")
def about():

    return "About Page"

if __name__ == "__main__":

    app.run(debug=True)

The corresponding home.html file can contain:

<!DOCTYPE html>
<html>

<head>
    <title>Flask App</title>
</head>

<body>

    <h1>Welcome {{ student }}</h1>

</body>

</html>
Key Points
  • Flask is a lightweight Python web framework.
  • Flask can be used to build websites and APIs.
  • Flask(__name__) creates the application object.
  • @app.route() maps a URL to a Python function.
  • render_template() renders HTML templates.
  • Jinja is used for dynamic template rendering.
  • request provides access to incoming request data.
  • request.form reads form data.
  • request.args reads query parameters.
  • jsonify() can create JSON responses.
  • redirect() redirects users to another URL.
  • url_for() generates URLs for endpoints.
  • The templates folder stores HTML templates.
  • The static folder stores CSS, JavaScript and image files.
  • Flask can work with databases such as SQLite and MySQL.
  • Flask is commonly used for backend and REST API development.

🧠 Quick Quiz

Question: Which decorator is commonly used to connect a URL to a Flask function?