Untitled

 avatar
unknown
plain_text
12 days ago
1.9 kB
0
Indexable
from flask import Flask, request, jsonify
import sqlite3
from datetime import datetime

app = Flask(__name__)

def init_db():
    with sqlite3.connect("temperature.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS temperatures (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                temperature INTEGER NOT NULL,
                timestamp TEXT NOT NULL
            )
        """)
        conn.commit()

@app.route('/store')
def store():
    data = request.args.get('data', default=None, type=int)
    if data is None:
        return "Error: No temperature provided.", 400
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with sqlite3.connect("temperature.db") as conn:
        cursor = conn.cursor()
        cursor.execute("INSERT INTO temperatures (temperature, timestamp) VALUES (?, ?)", (data, timestamp))
        conn.commit()
    
    return f"Stored temperature {data}°C at {timestamp}"

@app.route('/show_data')
def show_data():
    with sqlite3.connect("temperature.db") as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT temperature, timestamp FROM temperatures")
        data = cursor.fetchall()
    
    if not data:
        return "No data available."
    
    return jsonify([{"temperature": temp, "timestamp": ts} for temp, ts in data])

@app.route('/show_stats')
def show_stats():
    with sqlite3.connect("temperature.db") as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT MIN(temperature), MAX(temperature), AVG(temperature) FROM temperatures")
        stats = cursor.fetchone()
    
    if stats[0] is None:
        return "No data available."
    
    return jsonify({"min": stats[0], "max": stats[1], "average": round(stats[2], 2)})

if __name__ == '__main__':
    init_db()
    app.run(debug=True, port=8080)
Leave a Comment