{% extends "base.html" %} {% block title %}Flask Deployment - Data Science Lab{% endblock %} {% block content %}

๐Ÿ“– Application Architecture

Concept
Data Science Lab โ€” Full-Stack Architecture:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚              BROWSER (Frontend)             โ”‚
โ”‚  HTML/CSS/JS  โ”‚  Plotly.js  โ”‚  Fetch API    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
           โ”‚ HTTP Requests     โ”‚ WebSocket (future)
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚             FLASK (Backend)                 โ”‚
โ”‚  app.py (routes) โ”‚ api/routes.py (REST API) โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚           SERVICE LAYER                     โ”‚
โ”‚  ingestion โ”‚ pipeline โ”‚ validation โ”‚ stream โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚           MODEL LAYER                       โ”‚
โ”‚  ml_models โ”‚ timeseries โ”‚ nlp โ”‚ cv          โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚          DATABASE (SQLite)                  โ”‚
โ”‚  Star Schema โ”‚ Fact Tables โ”‚ Views          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

๐Ÿ“– REST API Design

Our application exposes a RESTful API at /api/*. Here are the available endpoints:

MethodEndpointDescription
GET/api/summaryDatabase summary statistics
GET/api/housinghousing data (with filters)
GET/api/transportTransport usage data
GET/api/edaExploratory data analysis stats
POST/api/model/trainTrain ML model
POST/api/model/predictPredict Price
GET/api/model/historyModel training history
POST/api/pipeline/runRun data pipeline
GET/api/pipeline/historyPipeline run history
POST/api/sql/executeExecute read-only SQL
POST/api/stream/generateGenerate streaming events
POST/api/stream/processProcess event window
GET/api/stream/statsStream statistics
POST/api/feedbackSubmit learning feedback
GET/api/validateRun data validations

API Usage Example

JavaScript
// GET request with query parameters
const response = await fetch('/api/housing?town=DOWNTOWN&property_type=MEDIUM');
const data = await response.json();
console.log(data.data);  // Array of housing records

// POST request with JSON body
const trainResponse = await fetch('/api/model/train', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify({model_type: 'random_forest'})
});
const result = await trainResponse.json();
console.log(`Rยฒ = ${result.metrics.r2_score}`);
Python
import requests

# Using the API from Python
base_url = "http://localhost:5000"

# Get housing data
resp = requests.get(f"{base_url}/api/housing", params={"town": "DOWNTOWN"})
data = resp.json()["data"]

# Train a model
resp = requests.post(f"{base_url}/api/model/train",
                     json={"model_type": "linear_regression"})
metrics = resp.json()["metrics"]
print(f"Model Rยฒ: {metrics['r2_score']:.4f}")

๐Ÿ“– Flask Best Practices

Python
# 1. Application Factory Pattern
def create_app():
    app = Flask(__name__)
    app.config.from_object('config')
    # Register blueprints
    from api.routes import api_bp
    app.register_blueprint(api_bp)
    return app

# 2. Error Handling
@app.errorhandler(404)
def not_found(e):
    return jsonify(error="Resource not found"), 404

@app.errorhandler(500)
def server_error(e):
    return jsonify(error="Internal server error"), 500

# 3. Input Validation
from werkzeug.utils import secure_filename

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files.get('file')
    if not file or not file.filename.endswith('.csv'):
        return jsonify(error="CSV file required"), 400
    filename = secure_filename(file.filename)
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

# 4. Security Headers
@app.after_request
def add_security_headers(response):
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'DENY'
    return response

๐Ÿ“– Production Deployment Checklist

Checklist
Pre-Deployment:
  โ˜ Set DEBUG = False in production
  โ˜ Use environment variables for secrets (SECRET_KEY, DB credentials)
  โ˜ Run all tests: pytest tests/
  โ˜ Check for SQL injection vulnerabilities (use parameterized queries โœ“)
  โ˜ Validate all user inputs

Deployment Options:
  1. Gunicorn + Nginx (Linux server)
     $ gunicorn -w 4 -b 0.0.0.0:8000 "app:create_app()"

  2. Docker
     FROM python:3.11-slim
     COPY requirements.txt .
     RUN pip install -r requirements.txt
     COPY . /app
     WORKDIR /app
     CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:8000", "app:create_app()"]

  3. Cloud (AWS/GCP/Azure)
     - AWS Elastic Beanstalk
     - Google App Engine
     - Azure App Service

Post-Deployment:
  โ˜ Set up logging (structured JSON logs)
  โ˜ Monitor API response times
  โ˜ Set up database backups
  โ˜ Configure HTTPS (SSL/TLS certificate)
๐Ÿงช Exercises

1. Test 3 API endpoints using the browser or curl. Verify the response format.

2. What would you change to support PostgreSQL instead of SQLite?

3. Write a Dockerfile for this application and explain each instruction.

{% endblock %}