Topic 1

Creating a Basic Web App with Flask

1. Introduction to Flask

  • What is Flask?

    • Flask is a lightweight, micro web framework written in Python.
    • It’s considered “micro” because it doesn’t come with built-in tools and libraries like some larger frameworks (e.g., Django). This means you can add only what you need, making it flexible and efficient.
  • Why use Flask?

    • It’s Pythonic, minimalistic, and quick to get started with.
    • Great for small to medium-sized web applications, RESTful services, and prototypes.

2. Setting Up Flask

  • Installation

pip install Flask

Hello World in Flask

from flask import Flask
app = Flask(__name__)

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

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

3. Routing in Flask

  • Routes define the URLs that your application implements and the views that should be triggered when those URLs are accessed.

  • Basic routing

    python
    @app.route('/hello') def hello(): return 'Hello Flask!'
  • Variable rules

    python
    @app.route('/user/<username>') def show_user_profile(username): return f'User {username}'

4. Templates with Jinja2

  • Flask uses the Jinja2 template engine, allowing you to send dynamic data and render it on HTML templates.

  • Setting up a template

    1. Create a folder named templates in your project directory.
    2. Create an HTML file within this folder, e.g., index.html.
    html
    <h1>Hello, {{ name }}!</h1>
    • Rendering a template
    python
    from flask import render_template @app.route('/hello/<name>') def hello_name(name): return render_template('index.html', name=name)

4. Templates with Jinja2

  • Flask uses the Jinja2 template engine, allowing you to send dynamic data and render it on HTML templates.

  • Setting up a template

    1. Create a folder named templates in your project directory.
    2. Create an HTML file within this folder, e.g., index.html.
    html
    <h1>Hello, {{ name }}!</h1>
    • Rendering a template
    python
    from flask import render_template @app.route('/hello/<name>') def hello_name(name): return render_template('index.html', name=name)

5. Static Files

  • For CSS, JavaScript, images, etc., Flask serves static files from the static folder.

  • Using static files

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