41 lines
1.2 KiB
Python
41 lines
1.2 KiB
Python
from flask import Blueprint, jsonify, request
|
|
from flask_jwt_extended import jwt_required
|
|
import pymysql
|
|
from config import Config
|
|
|
|
climate_bp = Blueprint('climate', __name__)
|
|
|
|
def get_db():
|
|
return pymysql.connect(
|
|
host=Config.MYSQL_HOST,
|
|
user=Config.MYSQL_USER,
|
|
password=Config.MYSQL_PASSWORD,
|
|
database=Config.MYSQL_DB,
|
|
cursorclass=pymysql.cursors.DictCursor
|
|
)
|
|
|
|
#GET — Récupérer toutes les données climatiques
|
|
@climate_bp.route('/', methods=['GET'])
|
|
@jwt_required()
|
|
def get_climate():
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute("SELECT * FROM climate_data ORDER BY timestamp DESC LIMIT 50")
|
|
data = cursor.fetchall()
|
|
db.close()
|
|
return jsonify(data), 200
|
|
|
|
#POST — Ajouter une donnée climatique
|
|
@climate_bp.route('/', methods=['POST'])
|
|
@jwt_required()
|
|
def add_climate():
|
|
body = request.get_json()
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute(
|
|
"INSERT INTO climate_data (temperature, humidity, pressure, luminosity) VALUES (%s, %s, %s, %s)",
|
|
(body.get('temperature'), body.get('humidity'), body.get('pressure'), body.get('luminosity'))
|
|
)
|
|
db.commit()
|
|
db.close()
|
|
return jsonify({'message': 'Donnée ajoutée avec succès'}), 201 |