Flask Basics and Setup

Jul 11, 2024

Introduction to Flask

Basics

  • Abdul from Pythonist introduces Flask
  • Flask: a micro web framework written in Python
  • No enforced dependencies or project layout
  • Initially simple, but scalable for complex applications
  • Extensions available to add functionality

Setting Up Flask

Virtual Environment

  1. Install virtualenv package: pip install virtualenv
  2. For Mac users: brew install virtualenv
  3. Create a virtual environment: virtualenv <env_name> <python_version(optional)>
  4. Activate the virtual environment:
    source <env_directory>/bin/activate
    

Installing Flask

  • Install Flask: pip install flask
  • Verify installation: pip freeze
  • Check import in Python interpreter:
    import flask
    

Building a Simple Flask Application

Creating the App

  1. Create a file app.py
  2. Import Flask and create an instance:
    from flask import Flask
    app = Flask(__name__)
    
  3. The application instance is an object of class Flask
    • Uses WSGI (Web Server Gateway Interface)
    • __name__ is typically the correct value for the application instance constructor

Defining Routes and View Functions

  • Routes: URLs mapped to functions
  • View Functions: Code executed when a specific URL is accessed
  • Define a route with app.route decorator:
    @app.route('/')
    def index():
        return 'Hello, World!'
    
  • Basic application created to handle requests to the root URL (/)

Conclusion

  • Learned Flask basics:
    • What Flask is
    • Setting up virtual environment
    • Installing Flask
    • Creating a basic application with routes and view functions
  • More to explore in upcoming videos