Earthquake Tracking

Let me break down this Flask application that creates an earthquake tracking API

  1. Initial Setup and Imports
from flask import Flask, jsonify
from earthquake_tracker import EarthquakeTracker
from datetime import datetime
import threading
import time

app = Flask(__name__)
tracker = EarthquakeTracker()

This section initializes the Flask application and creates an instance of the EarthquakeTracker class that handles the earthquake data processing.

  1. Background Data Update
def background_update():
    while True:
        tracker.update_historical_data()
        time.sleep(3600)  # Update every hour

This function runs in a separate thread and continuously updates the earthquake data every hour. The background thread ensures that the data stays fresh without blocking the main application.

  1. Home Route
@app.route('/')
def home():
    return jsonify({
        'status': 'running',
        'endpoints': {
            '/recent-earthquakes': 'Get 10 most recent earthquakes',
            '/prediction': 'Get earthquake prediction for next day'
        }
    })

The home endpoint provides API documentation, showing available endpoints and their purposes.

  1. Recent Earthquakes Endpoint
@app.route('/recent-earthquakes')
def recent_earthquakes():
    if tracker.historical_data is None:
        return jsonify({'error': 'No data available'}), 404
    
    recent_quakes = tracker.historical_data.sort_values('time', ascending=False).head(10)
    return jsonify([{
        'time': str(row['time']),
        'magnitude': row['magnitude'],
        'location': row['place'],
        'coordinates': [row['latitude'], row['longitude']]
    } for _, row in recent_quakes.iterrows()])

This endpoint returns the 10 most recent earthquakes. It:

  • Checks if data is available

  • Sorts the data by time

  • Returns formatted earthquake information including time, magnitude, location, and coordinates

  1. Prediction Endpoint
@app.route('/prediction')
def get_prediction():
    try:
        prediction = tracker.predict_next_earthquake()
        return jsonify({
            'prediction_date': str(datetime.now().date()),
            'predicted_earthquakes': prediction['predicted_earthquakes'],
            'confidence': prediction['confidence']
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

CopyI

This endpoint provides earthquake predictions for the next day, including:

  • The prediction date

  • Number of predicted earthquakes

  • Confidence level of the prediction

  • Error handling for prediction failures

  1. Application Startup
if __name__ == '__main__':
    update_thread = threading.Thread(target=background_update, daemon=True)
    update_thread.start()
    
    tracker.update_historical_data()
    
    app.run(debug=True)

The startup sequence:

  • Creates and starts a daemon thread for background updates

  • Performs initial data update

  • Starts the Flask application in debug mode

This application demonstrates good practices like:

  • Separation of concerns (data handling vs API endpoints)

  • Background processing for data updates

  • Proper error handling

  • Clear API documentation

  • RESTful endpoint design

  • Daemon threads for background tasks that automatically terminate when the main program exits

Updated on