{% extends "base.html" %} {% block title %}Flask Deployment - Data Science Lab{% endblock %} {% block content %}
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 โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโOur application exposes a RESTful API at /api/*. Here are the available endpoints:
| Method | Endpoint | Description |
|---|---|---|
| GET | /api/summary | Database summary statistics |
| GET | /api/housing | housing data (with filters) |
| GET | /api/transport | Transport usage data |
| GET | /api/eda | Exploratory data analysis stats |
| POST | /api/model/train | Train ML model |
| POST | /api/model/predict | Predict Price |
| GET | /api/model/history | Model training history |
| POST | /api/pipeline/run | Run data pipeline |
| GET | /api/pipeline/history | Pipeline run history |
| POST | /api/sql/execute | Execute read-only SQL |
| POST | /api/stream/generate | Generate streaming events |
| POST | /api/stream/process | Process event window |
| GET | /api/stream/stats | Stream statistics |
| POST | /api/feedback | Submit learning feedback |
| GET | /api/validate | Run data validations |
// 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}`);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}")# 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 responsePre-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)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.