🚀 Flask Server - Complete Beginner's Guide
What is Flask?
Flask is a lightweight Python web framework that makes it easy to create web applications and APIs.
Step 1: Basic Flask Setup
1.1 Install Flask
bash
pip install flask
1.2 Create a Basic Flask App (app.py
)
python
from flask import Flask # Create Flask application instance app = Flask(__name__) # Define a route - what happens when someone visits the homepage @app.route('/') def home(): return "Hello, World! This is my first Flask app!" # Run the application if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
1.3 Run Your First Flask App
bash
python app.py
Then visit: http://127.0.0.1:5000
Step 2: Adding HTML Templates
2.1 Create Folder Structure
text
my-flask-app/ ├── templates/ │ └── index.html ├── static/ │ └── style.css └── app.py
2.2 Create templates/index.html
html
<!DOCTYPE html> <html> <head> <title>My Flask App</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> </head> <body> <div class="container"> <h1>Welcome to My Flask App!</h1> <p>This is a custom HTML template.</p> <a href="/about">About Page</a> </div> </body> </html>
2.3 Create static/style.css
css
body { font-family: Arial, sans-serif; margin: 0; padding: 0; background-color: #f4f4f4; } .container { max-width: 800px; margin: 50px auto; padding: 20px; background: white; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); } h1 { color: #333; }
2.4 Update app.py
with Templates
python
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/about') def about(): return render_template('about.html', title='About Us') if __name__ == '__main__': app.run(debug=True)
Step 3: Handling Forms and User Input
3.1 Create a Form Template (templates/form.html
)
html
<!DOCTYPE html> <html> <head> <title>User Form</title> </head> <body> <h1>Contact Form</h1> <form method="POST" action="/submit"> <input type="text" name="username" placeholder="Your Name" required> <input type="email" name="email" placeholder="Your Email" required> <textarea name="message" placeholder="Your Message"></textarea> <button type="submit">Submit</button> </form> </body> </html>
3.2 Update app.py
with Form Handling
python
from flask import Flask, render_template, request, redirect, url_for app = Flask(__name__) @app.route('/form') def show_form(): return render_template('form.html') @app.route('/submit', methods=['POST']) def submit_form(): # Get data from form username = request.form['username'] email = request.form['email'] message = request.form['message'] # Process the data (you can save to database, send email, etc.) print(f"Received: {username}, {email}, {message}") # Redirect to success page return f"Thank you {username}! We received your message."
Step 4: Creating APIs with JSON
4.1 JSON API Example
python
from flask import Flask, jsonify, request import json app = Flask(__name__) # Sample data users = [ {'id': 1, 'name': 'John', 'email': 'john@example.com'}, {'id': 2, 'name': 'Jane', 'email': 'jane@example.com'} ] # GET API - Get all users @app.route('/api/users', methods=['GET']) def get_users(): return jsonify(users) # GET API - Get specific user @app.route('/api/users/<int:user_id>', methods=['GET']) def get_user(user_id): user = next((u for u in users if u['id'] == user_id), None) if user: return jsonify(user) return jsonify({'error': 'User not found'}), 404 # POST API - Create new user @app.route('/api/users', methods=['POST']) def create_user(): data = request.get_json() new_user = { 'id': len(users) + 1, 'name': data['name'], 'email': data['email'] } users.append(new_user) return jsonify(new_user), 201
Step 5: Complete Phishing Detector Example
Here's a simplified version of how I created your phishing detector:
5.1 Project Structure
text
phishing-detector/ ├── templates/ │ └── index.html ├── static/ │ └── style.css ├── models/ │ └── model.pkl └── app.py
5.2 Main Flask App (app.py
)
python
from flask import Flask, render_template, request, jsonify import pickle import pandas as pd app = Flask(__name__) # Load your machine learning model def load_model(): with open('models/phishing_model.pkl', 'rb') as f: return pickle.load(f) model = load_model() @app.route('/') def home(): return render_template('index.html') @app.route('/scan', methods=['POST']) def scan_url(): # Get URL from request data = request.get_json() url = data.get('url', '') # Extract features from URL features = extract_features(url) # Make prediction prediction = model.predict([features])[0] probability = model.predict_proba([features])[0][1] # Return result as JSON return jsonify({ 'url': url, 'is_phishing': bool(prediction), 'probability': float(probability) }) def extract_features(url): # Simplified feature extraction return [ len(url), # URL length url.count('.'), # Number of dots url.count('-'), # Number of hyphens int('https' in url), # Uses HTTPS # ... more features ] if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
5.3 HTML Template (templates/index.html
)
html
<!DOCTYPE html> <html> <head> <title>Phishing Detector</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> </head> <body> <div class="container"> <h1>Phishing Website Detector</h1> <input type="text" id="urlInput" placeholder="Enter URL to scan"> <button onclick="scanUrl()">Scan URL</button> <div id="result"></div> </div> <script> function scanUrl() { const url = document.getElementById('urlInput').value; fetch('/scan', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({url: url}) }) .then(response => response.json()) .then(data => { const resultDiv = document.getElementById('result'); if (data.is_phishing) { resultDiv.innerHTML = `🚨 Phishing detected! (${data.probability})`; } else { resultDiv.innerHTML = `✅ Safe website (${data.probability})`; } }); } </script> </body> </html>
Step 6: Key Flask Concepts
Routes
python
@app.route('/path') # GET by default @app.route('/path', methods=['GET', 'POST'])
Request Methods
python
request.form['field_name'] # Form data request.get_json() # JSON data request.args.get('param') # URL parameters
Responses
python
return "Text response" return render_template('page.html') return jsonify({'key': 'value'}) return redirect('/other-page')
Step 7: Running and Debugging
Development Mode
python
if __name__ == '__main__': app.run(debug=True) # Auto-reloads when code changes
Production Mode
python
if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) # Accessible from other devices
🎯 Quick Start Template
Here's a minimal template to get started immediately:
Create minimal_app.py
:
python
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/greet', methods=['POST']) def greet(): name = request.form.get('name', 'World') return f"Hello, {name}!" if __name__ == '__main__': app.run(debug=True)
Create templates/index.html
:
html
<!DOCTYPE html> <html> <body> <h1>My Flask App</h1> <form method="POST" action="/greet"> <input name="name" placeholder="Enter your name"> <button type="submit">Greet Me!</button> </form> </body> </html>
Run it:
bash
python minimal_app.py
That's it! You now have a working Flask application. Start with the minimal template and gradually add more features as you learn. Flask is very beginner-friendly and powerful! 🚀
0 Comments