.. _module5_flask_basics: 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 ---------------- .. code-block:: bash pip install flask -------------- Baby Steps: Your First Flask App --------------------------------- **The Simplest Flask App:** .. code-block:: python # 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:** .. code-block:: bash 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. .. code-block:: python 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) ------------------------------- .. code-block:: python from flask import Flask app = Flask(__name__) @app.route('/user/') def show_user(username): return f"👤 User Profile: {username}" @app.route('/post/') def show_post(post_id): return f"📝 Post ID: {post_id}" @app.route('/motivation/') 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 ```` for string parameters and ```` for integers. Flask automatically converts and validates! ✅ -------------- Returning HTML -------------- .. code-block:: python from flask import Flask app = Flask(__name__) @app.route('/') def home(): return ''' My Flask App 🎨
🚀

Welcome to Flask!

This is way cooler than plain text! ✨

''' if __name__ == '__main__': app.run(debug=True) -------------- Using Templates (Jinja2) ------------------------ Instead of writing HTML in strings, use templates! 📁 **Project Structure:** .. code-block:: text my_flask_app/ ├── app.py └── templates/ └── index.html **app.py:** .. code-block:: python 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:** .. code-block:: html Flask Template 🎨

Hello, {{ name }}! {{ emoji }}

Welcome to Flask Templates!

.. 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 ------------------------------------------- .. code-block:: python 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 ''' College Survival Guide 🎓

🎓 College Survival Guide 🎓

Your emergency handbook for college life! 📖

''' @app.route('/advice/') def advice(category): tips = SURVIVAL_TIPS.get(category, ['Category not found! 🤷']) tip = random.choice(tips) return f''' Survival Tip 💡
💡

{category.title()} Survival Tip

{tip}

← Back to Home
''' @app.route('/crisis/') def crisis(crisis_type): response = CRISIS_RESPONSES.get(crisis_type, "🤗 Whatever it is, you'll get through it! Take a deep breath. 💙") return f''' Emergency Response 🚨
🚨

Emergency Response Activated!

{response}

← Back to Safety
''' @app.route('/motivation/') 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''' Motivation Boost 💪
{emoji}

Motivation Level Check

Desperation Score: {desperation_score}/10

{message}

← Back to Home
''' 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) --------------------------- .. code-block:: python 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 '''
''' if __name__ == '__main__': app.run(debug=True) -------------- Error Handling -------------- .. code-block:: python from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Home Page 🏠" @app.errorhandler(404) def page_not_found(error): return ''' 404 - Lost? 🗺️
🤷‍♂️

404 - Page Not Found!

Looks like you're lost in the internet... 🌐

Go Home 🏠 ''', 404 @app.route('/help/') def help_route(problem): if problem == 'impossible': return '''

🌟 Nothing is Impossible! 🌟

Remember: Even experienced developers Google stuff daily! 💪
Take it step by step. You've got this! 🚀

← Back to Home ''', 404 return f"Help for: {problem}" if __name__ == '__main__': app.run(debug=True) -------------- Static Files (CSS, JS, Images) ------------------------------- **Project Structure:** .. code-block:: text my_flask_app/ ├── app.py ├── static/ │ ├── style.css │ └── logo.png └── templates/ └── index.html **Using static files:** .. code-block:: html My App 🎨 Logo

Hello from Flask! 👋

.. 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 ``