Activity 3.19
app.py
app.py (version 2)
What is Flask?
Flask is a web framework - think of it as a translator between your Python code and web browsers. When someone types a URL into their browser, Flask figures out which Python function should respond and what content to send back.
The Magic Formula:
Understanding the Web Request Cycle
Before we dive into code, let's understand what happens when you visit a website:
User types URL →
http://mysite.com/about
Browser sends request → "Hey server, I want the /about page"
Flask receives request → "I need to find which function handles /about"
Flask finds matching route → "Found it! The about() function handles this"
Function runs → Returns HTML content
Flask sends response → Browser displays the page
The Homepage: Your Website's Front Door
The homepage is the first page visitors see. In Flask, it's typically the route that responds to /
(the root URL).
Basic Homepage Structure
Breaking it down:
@app.route('/')
- The decorator that tells Flask "when someone visits the root URL, run the function below"def homepage():
- The function that gets executed (you can name this anything you want)return "Welcome!"
- The content that gets sent to the user's browser
Deep Dive: Route Decorators
Routes are like address labels for your functions. Let's explore different types:
1. Basic Routes
Important Notes:
Route paths are case-sensitive:
/About
is different from/about
Function names can be anything, but make them descriptive
Routes must start with
/
2. Multiple Routes to Same Function
Sometimes you want multiple URLs to show the same content:
Now all these URLs show the same page:
yoursite.com/
yoursite.com/home
yoursite.com/index
3. Routes with Trailing Slashes
Flask handles trailing slashes intelligently:
Last updated