-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
38 lines (29 loc) · 1.21 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from flask import Flask, request, jsonify
from pymongo import MongoClient
from pymongo.server_api import ServerApi
app = Flask(__name__)
client = MongoClient('mongodb+srv://USER:[email protected]/?retryWrites=true&w=majority&appName=Cluster0', server_api=ServerApi('1'))
db = client['sensor_data']
collection = db['readings']
@app.route('/post-data', methods=['POST'])
def post_data():
if request.method == 'POST':
data = request.json
humidity = data.get('Humidity')
temperature = data.get('Temperature')
mq_value = data.get('MQ Value')
if humidity is None or temperature is None or mq_value is None:
return jsonify({'status': 'error', 'message': 'Invalid data'}), 400
document = {
'temp': temperature,
'humidity': humidity,
'ppm': mq_value
}
collection.insert_one(document)
return jsonify({'status': 'success', 'message': 'Data saved successfully'}), 201
@app.route('/get-data', methods=['GET'])
def get_data():
data = collection.find({}, {"_id": 0})
return jsonify(list(data)), 200
if __name__ == '__main__':
app.run(host='IP4_ADDRESS', port=5000)