-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
41 lines (35 loc) · 1.34 KB
/
Copy pathapp.py
File metadata and controls
41 lines (35 loc) · 1.34 KB
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
39
40
41
from flask import Flask, request, jsonify
from datetime import datetime
from pymongo import MongoClient
import traceback # Import traceback module
app = Flask(__name__)
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['traffic_db']
traffic_collection = db['traffic_data']
# Route to receive traffic data from data-generating nodes
@app.route('/traffic', methods=['POST'])
def receive_traffic_data():
try:
data = request.json
if not data:
return 'No JSON data received', 400
data['timestamp'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
traffic_collection.insert_one(data)
return 'Traffic data received successfully!', 200
except Exception as e:
traceback.print_exc() # Print exception traceback
return f'Error processing request: {e}', 500
# Route to perform analysis and present data to the user
@app.route('/analysis', methods=['GET'])
def analysis():
try:
avg_speed = traffic_collection.aggregate([
{"$group": {"_id": None, "avg_speed": {"$avg": "$speed"}}}
])
avg_speed = list(avg_speed)[0]['avg_speed']
return f'Average Speed: {avg_speed} kmph', 200
except Exception as e:
return f'Error performing analysis: {e}', 500
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)