Lesson 1: Introduction to Flask

Flask is a lightweight and flexible web framework for Python that enables developers to build web applications quickly and efficiently. It is known for its simplicity and minimalism, making it a great choice for beginners and small to medium-sized projects.

Lesson Outline:

  1. Setting Up a Flask Project
  2. Creating Routes and Views
  3. Handling Forms and Templates

1. Setting Up a Flask Project

Installing Flask:

  • Use pip to install Flask:
    pip install Flask
  • Verify the installation:
    python -m flask –version

Creating a Basic Project Structure:

  • py: Main application file
  • templates/: Directory for HTML templates
  • static/: Directory for CSS, JavaScript, images

Basic Flask App Example:

from flask import Flask

app = Flask(__name__)

 

@app.route(‘/’)

def home():

return “Hello, Flask!”

 

if __name__ == ‘__main__’:

app.run(debug=True)

  • Run the app:
    python app.py
  • Visit http://127.0.0.1:5000/to see the output.

2. Creating Routes and Views

Understanding Routes:

  • Routes define the URL patterns for your web application.
  • The @app.route()decorator binds a URL to a function (view).

Example:

@app.route(‘/about’)

def about():

return “This is the About page.”

  • Access this view via http://127.0.0.1:5000/about

Dynamic Routes:

@app.route(‘/user/<username>’)

def show_user(username):

return f”Hello, {username}!”

  • This handles dynamic URLs like /user/John

3. Handling Forms and Templates

Using HTML Templates:

  • Create a templates

Add an index.html file:

<!DOCTYPE html>

<html>

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

<body>

<h1>Welcome to Flask!</h1>

</body>

  • </html>

Rendering Templates in Flask:

from flask import render_template

 

@app.route(‘/’)

def home():

return render_template(‘index.html’)

Handling Forms:

python
Create a simple form in form.html:
<form method=”POST” action=”/submit”>

<input type=”text” name=”username” placeholder=”Enter your name”>

<input type=”submit” value=”Submit”>

  • </form>

Processing Form Data:

python
from flask import request

 

@app.route(‘/submit’, methods=[‘POST’])

def submit():

username = request.form[‘username’]

return f”Hello, {username}!”

Conclusion:

  • Flask provides a simple yet powerful framework to build web applications.
  • You’ve learned how to set up a project, create routes, and handle forms with templates.

Next, we’ll dive deeper into advanced Flask features like blueprints, REST APIs, and database integration.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *