Introduction to Flask

  1. What Is Flask?



  2. Installing Flask

  3. python3 -m venv venv
    source venv/bin/activate
    
    pip install flask
    


  4. Your First Flask Application

  5. from flask import Flask
    
    app = Flask(__name__)
    
    @app.route("/")
    def home():
        return "Hello, Flask!"
    
    if __name__ == "__main__":
        app.run(debug=True)
    
    python3 app.py
    


  6. Routing: Connecting URLs to Functions

  7. @app.route("/hello")
    def greet():
        return "Hello!"
    

    @app.route("/user/<name>")
    def user(name):
        return f"User: {name}"
    

    @app.route("/square/<int:num>")
    def square(num):
        return str(num * num)
    


  8. Templates: Rendering HTML with Jinja2

  9. project/
    ├── app.py
    └── templates/
        └── index.html
    
    <!-- templates/index.html -->
    <h1>Hello, {{ name }}!</h1>
    
    from flask import render_template
    
    @app.route("/hello/<name>")
    def hello(name):
        return render_template("index.html", name=name)
    



  10. Handling POST Requests

  11. @app.route("/submit", methods=["GET", "POST"])
    def submit():
        if request.method == "POST":
            data = request.form["username"]
            return f"Received: {data}"
        return "Send a POST request!"
    


  12. Using JSON and Building APIs

  13. from flask import jsonify
    
    @app.route("/api/user/<int:id>")
    def api_user(id):
        return jsonify({"id": id, "name": "Alice"})
    



  14. Flask Application Structure (Recommended Layout)

  15. myapp/
    ├── app.py
    ├── static/
    │   └── style.css
    ├── templates/
    │   ├── base.html
    │   └── index.html
    └── routes/
        └── home.py
    



  16. Development vs. Production



  17. Flask Extensions (Powerful Add-ons)



Flask Application Overview

  1. What Is Flask?



  2. Installing and Running a Flask Application



  3. Understanding the Flask Application Object



  4. Routing Fundamentals



  5. Template Rendering



  6. Handling Requests and Forms



  7. Flask Application Configuration



  8. Using Flask Extensions



  9. The Application Factory Pattern



  10. Blueprints (Modular Applications)



  11. Static Files and Templates



  12. Error Handling



Flask Routing

  1. What Is Routing in Flask?



  2. Basic Route Definition



  3. Defining Routes with URLs



  4. Dynamic URL Parameters



  5. URL Building with url_for()



  6. HTTP Methods (GET, POST, etc.)



  7. Handling Query Parameters



  8. Route Defaults



  9. Redirects



  10. Custom Error Routes



  11. Routing Inside Blueprints



  12. Advanced Routing Features



Flask Variable Rules

  1. What Are Variable Rules in Flask?



  2. Basic Syntax of Variable Rules



  3. Built-In Converters



  4. Default Converter: string



  5. Using the int Converter



  6. Using the float and path Converters



  7. Using the uuid Converter



  8. Multiple Variable Rules in One Route



  9. Variable Rules and url_for()



  10. Trailing Slashes and Variable Rules



  11. Custom Converters (Overview)



  12. Error Handling with Variable Rules



Flask URL Building

  1. What Is URL Building in Flask?



  2. Basic Usage of url_for() in Python



  3. URL Building with Variable Rules



  4. Adding Query Parameters with url_for()



  5. Using url_for() in Templates (Jinja2)



  6. URL Building for Static Files



  7. Custom Endpoint Names



  8. URL Building with Blueprints



  9. Building Absolute URLs (_external and _scheme)



  10. Using url_for() with redirect()




Flask HTTP Methods

  1. What Are HTTP Methods in Flask?



  2. Defining Allowed Methods in @app.route()



  3. GET Method



  4. POST Method



  5. PUT Method



  6. PATCH Method



  7. DELETE Method



  8. HEAD Method



  9. OPTIONS Method



  10. Handling Different Methods Inside a Single View



  11. Using @app.get, @app.post, @app.put (Shorthand Decorators)



  12. Method-Specific Routing Examples



  13. 405 Method Not Allowed



  14. Summary Table of HTTP Methods

  15. Method Purpose Idempotent?
    GET Retrieve data Yes
    POST Create or submit data No
    PUT Replace entire resource Yes
    PATCH Modify part of resource Sometimes
    DELETE Remove resource Yes
    HEAD Headers only Yes
    OPTIONS Discover supported methods Yes


Flask Templates

  1. What Are Templates in Flask?



  2. Setting Up the Templates Folder



  3. Rendering Templates with render_template()



  4. Passing Data to Templates



  5. Jinja2 Template Syntax: Variables



  6. Jinja2 Control Structures



  7. Template Inheritance



  8. Using Layout Blocks



  9. Using Static Files Inside Templates



  10. Template Filters



  11. Including Templates



  12. Escaping and Safe Rendering



  13. Macros in Templates



  14. Template Comments



  15. Using url_for() in Templates



  16. Custom Template Folders



  17. Rendering Non-HTML Templates



  18. Common Mistakes and Best Practices



Flask Static Files

  1. What Are Static Files in Flask?



  2. Default Static Folder Structure



  3. Using url_for() to Link Static Files



  4. Serving Static Files Automatically



  5. Using Static Files in Templates



  6. Customizing the Static Folder Location



  7. Serving Static Files Manually (Advanced)



  8. Static Files Versioning (Cache-Busting)



  9. Using Static Files in Blueprints



  10. Static vs Template Files (Important Distinction)



  11. Favicon Handling




Flask Request Object

  1. What Is the Flask Request Object?



  2. Accessing HTTP Methods



  3. Reading Query Parameters (request.args)



  4. Reading Form Data (request.form)



  5. Reading JSON Data (request.json)



  6. Accessing Form and JSON Together (request.values)



  7. Accessing Headers (request.headers)



  8. Accessing Cookies (request.cookies)



  9. Handling File Uploads (request.files)



  10. Reading Route Variables (request.view_args)



  11. Getting the Full Request URL

  12. @app.route('/info')
    def info():
        return {
            "url": request.url,
            "path": request.path,
            "base": request.base_url,
        }
    


  13. Accessing Client IP Address



  14. Detecting AJAX Requests



  15. Checking MIME Types



  16. Working with Request Data Safely



  17. Summary Table of Common Attributes

  18. Attribute Description
    request.method HTTP method
    request.args Query parameters
    request.form Form POST data
    request.json JSON payload
    request.files Uploaded files
    request.headers HTTP headers
    request.cookies Client cookies
    request.view_args Route variables
    request.url Full URL
    request.remote_addr Client IP


Flask Sending Form Data to Template

  1. What Does It Mean to Send Form Data to a Template?



  2. Typical Workflow for Sending Form Data

    1. User fills a form in an HTML template.
    2. Browser sends a POST request.
    3. Flask receives the form data via request.form.
    4. Flask passes this data to another template using render_template().
    5. Template displays the submitted values.


  3. Creating a Simple Form in a Template



  4. Receiving Form Data in Flask



  5. Displaying Form Data in the Template



  6. Sending Multiple Form Fields



  7. Handling Empty or Missing Form Fields



  8. Sending Form Data to Another Template After Validation



  9. Sending Form Data to Template Using Jinja2 Loops



  10. Preserving Form Input After Submission



  11. Passing Form Data with Redirect–POST–Redirect Pattern



Flask Cookies

  1. What Are Cookies in Flask?



  2. Accessing Cookies (request.cookies)



  3. Setting Cookies in Flask



  4. Cookie Options (Expiration, Path, Domain)



  5. Deleting Cookies



  6. Using Cookies to Maintain User Preferences



  7. Storing JSON or Large Data in Cookies



  8. Cookies vs Flask Sessions



  9. Checking If a Cookie Exists



  10. Security Best Practices for Cookies



Flask Sessions

  1. What Are Sessions in Flask?



  2. Enabling Sessions (SECRET_KEY)



  3. Storing Data in Session



  4. Retrieving Session Data



  5. Checking If Session Keys Exist



  6. Removing Items from Session



  7. Session Lifetime (Permanent Sessions)



  8. How Flask Stores Sessions Internally



  9. Using Sessions with Forms (Common Use Case)



  10. Using Sessions for Login Systems



  11. Securing Sessions



  12. When to Use Sessions vs Cookies



  13. Summary of Session Methods

  14. Operation Code Example
    Set session value session['key'] = value
    Get session value session.get('key')
    Check existence 'key' in session
    Remove value session.pop('key')
    Clear all session.clear()
    Make session permanent session.permanent = True


Flask Redirect & Errors

  1. Using redirect() with url_for()



  2. Redirecting to External URLs



  3. Using Different Redirect Status Codes



  4. Redirect After Form Submission (POST → Redirect → GET)



  5. Basic Error Handling Using abort()



  6. Creating Custom Error Pages



  7. Handling 500 Internal Server Errors



  8. Handling Multiple Errors in One Place



  9. Raising Custom Error Messages



  10. Redirecting Instead of Showing an Error



  11. Error Pages with Jinja2 and Dynamic Data



  12. Using Blueprints for Error Handling



  13. Summary of Redirect and Error Functions

  14. Function Purpose
    redirect() Send browser to another URL
    url_for() Build a route URL
    abort() Raise an HTTP error
    @app.errorhandler() Custom error page for an HTTP code


Flask Message Flashing

  1. What Is Message Flashing in Flask?



  2. Enabling Flash Messages



  3. Flashing a Message



  4. Displaying Flash Messages in Templates



  5. Flashing Messages with Categories



  6. Redirect–Flash–Render Pattern



  7. Using Flash Messages With Forms



  8. Storing Multiple Flash Messages



  9. Using Flash Message Filters



  10. Displaying Flash Messages Using Bootstrap



  11. Flashing Messages in Blueprints



  12. Advanced: Flashing with Additional Payload



  13. Clearing All Flash Messages (Rare Case)



Flask File Uploading

  1. Common upload use cases:


  2. File uploading requires:


  3. Flask stores uploaded files in memory or temporary files before you save them.


  4. Creating a File Upload Form



  5. Receiving and Saving Uploaded Files



  6. Ensuring the Upload Directory Exists



  7. Securing File Uploads with secure_filename()



  8. Restricting Allowed File Types



  9. Handling Multiple File Uploads



  10. Retrieving Uploaded Files (Serving Them)



  11. Limiting Maximum File Size



  12. Handling Upload Errors



  13. Using Flash Messages for Upload Feedback



  14. File Uploading with Blueprints



  15. Security Best Practices for File Uploads



Flask Extensions

  1. What Are Flask Extensions?



  2. Installing Flask Extensions



  3. Commonly Used Flask Extensions (Overview)



  4. Basic Extension Initialization (Single-File App)



  5. Application Factory Pattern and init_app()



  6. Example: Using Flask-SQLAlchemy



  7. Example: Flask-WTF (Forms & CSRF)



  8. Example: Flask-Login (User Sessions)



  9. Configuration Patterns for Extensions



  10. Finding and Evaluating Flask Extensions



  11. Writing Your Own Simple Extension (Overview)



Flask Mail

  1. What Is Flask-Mail?



  2. Installing Flask-Mail



  3. Basic Configuration



  4. Sending a Basic Email



  5. Sending HTML Emails



  6. Sending Emails Using Templates



  7. Sending Emails with Attachments



  8. Sending to Multiple Recipients



  9. Default Sender



  10. Asynchronous Email Sending



  11. Error Handling



  12. Flask-Mail vs Other Mail Solutions



Flask SQLite

  1. Introduction to SQLite in Flask



  2. Using SQLite with Python’s sqlite3 Module



  3. Creating an SQLite Database



  4. Inserting Data into SQLite



  5. Fetching Data



  6. Using SQLite with Flask Application Context



  7. Using SQLite with Flask-SQLAlchemy (Recommended)



  8. Querying with SQLAlchemy ORM



  9. Using Flask-Migrate with SQLite



  10. Best Practices When Using SQLite with Flask



Flask Deployment

  1. Introduction to Deploying Flask Applications



  2. Preparing Your Flask App for Deployment



  3. Deploying with Gunicorn (Linux/Unix)



  4. Deploying with uWSGI (Alternative)



  5. Setting Up NGINX as a Reverse Proxy



  6. Running Flask as a Systemd Service



  7. Deploying on Heroku



  8. Deploying on PythonAnywhere



  9. Deploying on AWS EC2



  10. Serving Static Files in Production



  11. Using a Virtual Environment



  12. Enabling HTTPS with Certbot (Let's Encrypt)



  13. Environment Variables (Production Settings)



  14. Best Practices for Flask Deployment