Flask Basics: Web Development in Pythonยถ
Introductionยถ
Flask is a lightweight and flexible Python web framework that makes building web applications easy and fun. Itโs perfect for beginners and powerful enough for production applications! ๐
Note
Flask follows the motto โmicro but mightyโ ๐ช. It gives you the essentials to build web apps without forcing you into a specific way of doing things. Perfect for learning and rapid prototyping!
Installing Flaskยถ
pip install flask
Baby Steps: Your First Flask Appยถ
The Simplest Flask App:
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World! ๐"
if __name__ == '__main__':
app.run(debug=True)
Run it:
python app.py
Open browser: http://127.0.0.1:5000/ โจ
Note
debug=True enables auto-reload and better error messages. Super helpful during development! But remember: NEVER use debug mode in production! ๐ซ
Understanding Routesยถ
Routes tell Flask which function to run for different URLs.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "๐ Welcome Home!"
@app.route('/about')
def about():
return "๐ About Us: We teach Python!"
@app.route('/contact')
def contact():
return "๐ง Contact: email@example.com"
if __name__ == '__main__':
app.run(debug=True)
Try these URLs: - http://127.0.0.1:5000/ - http://127.0.0.1:5000/about - http://127.0.0.1:5000/contact
Dynamic Routes (URL Parameters)ยถ
from flask import Flask
app = Flask(__name__)
@app.route('/user/<username>')
def show_user(username):
return f"๐ค User Profile: {username}"
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f"๐ Post ID: {post_id}"
@app.route('/motivation/<int:desperation_score>')
def motivation(desperation_score):
if desperation_score < 3:
return "๐ช You're doing great! Keep going!"
elif desperation_score < 7:
return "๐
Hang in there! Coffee break recommended."
else:
return "๐ Emergency! Take a break. You've got this! ๐ซ"
if __name__ == '__main__':
app.run(debug=True)
Try: - http://127.0.0.1:5000/user/alice - http://127.0.0.1:5000/post/42 - http://127.0.0.1:5000/motivation/8
Note
Use <variable> for string parameters and <int:variable> for integers. Flask automatically converts and validates! โ
Returning HTMLยถ
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return '''
<!DOCTYPE html>
<html>
<head>
<title>My Flask App ๐จ</title>
<style>
body {
font-family: Arial;
text-align: center;
padding: 50px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
h1 { font-size: 48px; }
.emoji { font-size: 64px; }
</style>
</head>
<body>
<div class="emoji">๐</div>
<h1>Welcome to Flask!</h1>
<p>This is way cooler than plain text! โจ</p>
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True)
Using Templates (Jinja2)ยถ
Instead of writing HTML in strings, use templates! ๐
Project Structure:
my_flask_app/
โโโ app.py
โโโ templates/
โโโ index.html
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html',
name='Student',
emoji='๐')
if __name__ == '__main__':
app.run(debug=True)
templates/index.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask Template ๐จ</title>
<style>
body {
font-family: Arial;
text-align: center;
padding: 50px;
background: #f0f0f0;
}
.card {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
max-width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="card">
<h1>Hello, {{ name }}! {{ emoji }}</h1>
<p>Welcome to Flask Templates!</p>
</div>
</body>
</html>
Note
Flask uses Jinja2 templating. {{ variable }} displays values, {% for %} creates loops, {% if %} adds conditions. Itโs like Python in HTML! ๐ฏ
Real-World Example: College Survival Guideยถ
from flask import Flask, render_template
import random
app = Flask(__name__)
# Survival tips database ๐ก
SURVIVAL_TIPS = {
'academic': [
"๐ Start assignments early (we know you won't, but we have to say it)",
"๐ค Form study groups (even if they become gaming sessions)",
"๐ Attend classes (Netflix can wait!)",
"๐ฏ Set realistic goals (not 'finish entire syllabus tonight')",
"โ Coffee is your friend, but so is sleep!"
],
'social': [
"๐ Join clubs and activities",
"๐ฌ Network with seniors (they know the shortcuts)",
"๐ค Be kind to everyone (you never know who'll save you in group projects)",
"๐ฎ Balance is key: study hard, play harder!",
"๐ Remember: everyone is faking confidence"
],
'mental': [
"๐ง Take breaks (burnout is real!)",
"๐ Celebrate small wins",
"๐ช It's okay to ask for help",
"๐ Your worth isn't defined by grades",
"๐ญ Imposter syndrome? Everyone has it!"
]
}
CRISIS_RESPONSES = {
'exam': "๐จ Emergency Protocol: 1) Don't panic 2) Make a study plan 3) Start NOW 4) Breathe! You've got this! ๐ช",
'project': "๐ฅ Project Crisis: Break it into tiny chunks. Do ONE thing. Then another. Progress > Perfection! ๐ฏ",
'life': "๐ Life feels overwhelming? That's normal! Talk to someone. Take a walk. Remember: this too shall pass. ๐",
'deadline': "โฐ Deadline approaching? Priority mode activated! Turn off distractions. Focus on must-haves. You can do this! ๐"
}
@app.route('/')
def home():
return '''
<html>
<head>
<title>College Survival Guide ๐</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 50px auto;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.container {
background: white;
padding: 40px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}
h1 { color: #667eea; text-align: center; }
.nav-buttons {
display: flex;
justify-content: space-around;
margin-top: 30px;
flex-wrap: wrap;
}
.btn {
background: #667eea;
color: white;
padding: 15px 25px;
text-decoration: none;
border-radius: 8px;
margin: 10px;
display: inline-block;
transition: transform 0.2s;
}
.btn:hover {
transform: scale(1.05);
background: #764ba2;
}
.emergency {
background: #e74c3c;
}
</style>
</head>
<body>
<div class="container">
<h1>๐ College Survival Guide ๐</h1>
<p style="text-align: center; font-size: 18px;">
Your emergency handbook for college life! ๐
</p>
<div class="nav-buttons">
<a href="/advice/academic" class="btn">๐ Academic Tips</a>
<a href="/advice/social" class="btn">๐ Social Life</a>
<a href="/advice/mental" class="btn">๐ง Mental Health</a>
<a href="/crisis/exam" class="btn emergency">๐จ Exam Crisis</a>
<a href="/crisis/project" class="btn emergency">๐ฅ Project Panic</a>
<a href="/crisis/deadline" class="btn emergency">โฐ Deadline Alert</a>
<a href="/motivation/5" class="btn">๐ช Need Motivation</a>
</div>
</div>
</body>
</html>
'''
@app.route('/advice/<category>')
def advice(category):
tips = SURVIVAL_TIPS.get(category, ['Category not found! ๐คท'])
tip = random.choice(tips)
return f'''
<html>
<head>
<title>Survival Tip ๐ก</title>
<style>
body {{
font-family: Arial;
max-width: 600px;
margin: 100px auto;
padding: 20px;
text-align: center;
}}
.tip-card {{
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 40px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}}
.emoji {{ font-size: 64px; margin: 20px 0; }}
h2 {{ font-size: 32px; }}
a {{
color: white;
background: rgba(255,255,255,0.2);
padding: 10px 20px;
border-radius: 5px;
text-decoration: none;
display: inline-block;
margin-top: 20px;
}}
</style>
</head>
<body>
<div class="tip-card">
<div class="emoji">๐ก</div>
<h2>{category.title()} Survival Tip</h2>
<p style="font-size: 20px; line-height: 1.6;">{tip}</p>
<a href="/">โ Back to Home</a>
</div>
</body>
</html>
'''
@app.route('/crisis/<crisis_type>')
def crisis(crisis_type):
response = CRISIS_RESPONSES.get(crisis_type,
"๐ค Whatever it is, you'll get through it! Take a deep breath. ๐")
return f'''
<html>
<head>
<title>Emergency Response ๐จ</title>
<style>
body {{
font-family: Arial;
max-width: 600px;
margin: 100px auto;
padding: 20px;
text-align: center;
}}
.emergency-card {{
background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
color: white;
padding: 40px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
animation: pulse 2s infinite;
}}
@keyframes pulse {{
0%, 100% {{ transform: scale(1); }}
50% {{ transform: scale(1.02); }}
}}
.emoji {{ font-size: 64px; margin: 20px 0; }}
h2 {{ font-size: 32px; }}
a {{
color: white;
background: rgba(255,255,255,0.3);
padding: 10px 20px;
border-radius: 5px;
text-decoration: none;
display: inline-block;
margin-top: 20px;
}}
</style>
</head>
<body>
<div class="emergency-card">
<div class="emoji">๐จ</div>
<h2>Emergency Response Activated!</h2>
<p style="font-size: 20px; line-height: 1.6;">{response}</p>
<a href="/">โ Back to Safety</a>
</div>
</body>
</html>
'''
@app.route('/motivation/<int:desperation_score>')
def motivation(desperation_score):
if desperation_score < 3:
message = "๐ You're absolutely crushing it! Keep that energy! ๐ช"
color = "#2ecc71"
emoji = "๐"
elif desperation_score < 7:
message = "๐
Hanging in there! Remember: progress over perfection! ๐"
color = "#f39c12"
emoji = "โ"
else:
message = "๐ EMERGENCY MOTIVATION DEPLOYED! You are stronger than you think. This is temporary. You've got this! ๐ซ๐"
color = "#e74c3c"
emoji = "๐"
return f'''
<html>
<head>
<title>Motivation Boost ๐ช</title>
<style>
body {{
font-family: Arial;
max-width: 600px;
margin: 100px auto;
padding: 20px;
text-align: center;
}}
.motivation-card {{
background: {color};
color: white;
padding: 40px;
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
}}
.emoji {{ font-size: 80px; margin: 20px 0; }}
h2 {{ font-size: 28px; }}
.score {{
background: rgba(255,255,255,0.3);
padding: 10px 20px;
border-radius: 10px;
display: inline-block;
margin: 20px 0;
}}
a {{
color: white;
background: rgba(0,0,0,0.2);
padding: 10px 20px;
border-radius: 5px;
text-decoration: none;
display: inline-block;
margin-top: 20px;
}}
</style>
</head>
<body>
<div class="motivation-card">
<div class="emoji">{emoji}</div>
<h2>Motivation Level Check</h2>
<div class="score">Desperation Score: {desperation_score}/10</div>
<p style="font-size: 22px; line-height: 1.6;">{message}</p>
<a href="/">โ Back to Home</a>
</div>
</body>
</html>
'''
if __name__ == '__main__':
app.run(debug=True)
Note
This app demonstrates dynamic routing, HTML styling, and how to create an interactive survival guide! Notice how each route handles different scenarios with appropriate responses. ๐ฏ
HTTP Methods (GET vs POST)ยถ
from flask import Flask, request
app = Flask(__name__)
@app.route('/search')
def search():
# GET parameters from URL: /search?q=python
query = request.args.get('q', 'nothing')
return f"๐ You searched for: {query}"
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
# POST data from form
name = request.form.get('name')
return f"โ
Form submitted! Hello, {name}!"
else:
# Show form
return '''
<form method="POST">
<input type="text" name="name" placeholder="Your name" required>
<button type="submit">Submit ๐</button>
</form>
'''
if __name__ == '__main__':
app.run(debug=True)
Error Handlingยถ
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Home Page ๐ "
@app.errorhandler(404)
def page_not_found(error):
return '''
<html>
<head>
<title>404 - Lost? ๐บ๏ธ</title>
<style>
body {
font-family: Arial;
text-align: center;
padding: 100px;
background: #f0f0f0;
}
.emoji { font-size: 100px; }
h1 { color: #e74c3c; }
</style>
</head>
<body>
<div class="emoji">๐คทโโ๏ธ</div>
<h1>404 - Page Not Found!</h1>
<p>Looks like you're lost in the internet... ๐</p>
<a href="/">Go Home ๐ </a>
</body>
</html>
''', 404
@app.route('/help/<problem>')
def help_route(problem):
if problem == 'impossible':
return '''
<html>
<body style="text-align: center; padding: 50px; font-family: Arial;">
<h1>๐ Nothing is Impossible! ๐</h1>
<p style="font-size: 20px;">
Remember: Even experienced developers Google stuff daily! ๐ช<br>
Take it step by step. You've got this! ๐
</p>
<a href="/">โ Back to Home</a>
</body>
</html>
''', 404
return f"Help for: {problem}"
if __name__ == '__main__':
app.run(debug=True)
Static Files (CSS, JS, Images)ยถ
Project Structure:
my_flask_app/
โโโ app.py
โโโ static/
โ โโโ style.css
โ โโโ logo.png
โโโ templates/
โโโ index.html
Using static files:
<!DOCTYPE html>
<html>
<head>
<title>My App ๐จ</title>
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
<img src="{{ url_for('static', filename='logo.png') }}" alt="Logo">
<h1>Hello from Flask! ๐</h1>
</body>
</html>
Note
Flask serves files from the static/ folder automatically. Use url_for('static', filename='...') to generate correct URLs. ๐
Tasksยถ
Task 1: Personal Portfolio Website
Create a Flask app with routes: / (home with intro), /projects (list of projects with emojis), /skills (programming skills with progress bars in HTML), /contact (contact info). Use colorful HTML/CSS styling with gradients and emojis. Make each page visually distinct! ๐จ
Hint: Create separate routes for each page. Use inline CSS or create a static/style.css file. Add emojis liberally! Return HTML strings with <style> tags.
Task 2: Mood Tracker Web App
Create a Flask app that tracks your mood. Route / shows a form to select mood (๐ Happy, ๐ Neutral, ๐ข Sad) and a note. Route /mood/<mood_type> displays an encouraging message based on mood. Store data in a Python list (no database needed). Show mood history on homepage.
Hint: Use a global list to store moods: moods = []. Access form data with request.form.get(). Use methods=['GET', 'POST'] for form route.
Task 3: Random Advice Generator
Build a โCollege Survival Adviceโ web app with categories: Academic ๐, Social ๐, Mental Health ๐ง, Career ๐ผ. Route / shows category buttons. Route /advice/<category> displays random advice from a predefined dictionary. Add a โCrisis Helpโ section with /crisis/<type> that redirects to counseling resources.
Hint: Store advice in a dictionary of lists. Use import random and random.choice(list). Create styled HTML responses with emergency colors for crisis routes.
Task 4: Study Session Timer Page
Create a Pomodoro-style timer app. Route / explains the technique with emojis. Route /timer/<int:minutes> displays a motivational message based on duration (25 min = ๐
Pomodoro, 5 min = โ Break, etc.). Add routes /start, /break, /finish with appropriate encouragement messages!
Hint: No actual timer needed - just display messages! Use URL parameters for duration. Style each route differently with CSS gradients. Add encouraging emojis and messages.
Task 5: Simple Blog Platform
Create a mini-blog with: / (homepage listing post titles), /post/<int:id> (display post content), /about (about the blog). Store 5 sample posts in a list of dictionaries with keys: id, title, content, date, emoji. Make it colorful with CSS! ๐
Hint: Posts list: [{'id': 1, 'title': '...', 'content': '...', 'emoji': '๐'}]. Loop through posts on homepage. Use id to find specific post in /post/<int:id> route.
Summaryยถ
Flask is a micro web framework - simple yet powerful! ๐ช
@app.route()decorator defines URL routesUse
<variable>in routes for dynamic URLsrender_template()serves HTML templates (Jinja2)Templates use
{{ variable }}for variables,{% %}for logicrequest.argsgets URL parameters (GET)request.formgets form data (POST)methods=['GET', 'POST']handles both methodsError handlers customize error pages
static/folder serves CSS, JS, imagesdebug=Truefor development,Falsefor productionFlask makes web development fun and approachable! ๐