-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsensors.py
66 lines (53 loc) · 1.92 KB
/
sensors.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import requests
from flask import Flask, Response, jsonify
from flask import request as flask_request
from ddtrace import tracer, patch, config
from ddtrace.contrib.flask import TraceMiddleware
from bootstrap import create_app, db
from models import Network, Sensor
import random
sensors = []
# Tracer configuration
tracer.configure(hostname='agent')
tracer.set_tags({'env': 'workshop'})
patch(requests=True)
# enable distributed tracing for requests
# to send headers (globally)
config.requests['distributed_tracing'] = True
app = create_app()
traced_app = TraceMiddleware(app, tracer, service='sensors-api', distributed_tracing=True)
@app.route('/')
def hello():
return Response({'Hello from Sensors': 'world'}, mimetype='application/json')
@app.route('/sensors', methods=['GET', 'POST'])
def get_sensors():
if flask_request.method == 'GET':
sensors = Sensor.query.all()
system_status = []
for sensor in sensors:
system_status.append(sensor.serialize())
return jsonify({'sensor_count': len(system_status),
'system_status': system_status})
elif flask_request.method == 'POST':
sensors.append({'sensor_no': len(sensors) + 1, 'value': random.randint(1,100)})
return jsonify(sensors)
else:
err = jsonify({'error': 'Invalid request method'})
err.status_code = 405
return err
@app.route('/sensors/<id>/')
def sensor(id):
return jsonify(Sensor.query.get(id).serialize())
@app.route('/refresh_sensors')
def refresh_sensors():
sensors = simulate_all_sensors()
return jsonify({'sensor_count': len(sensors),
'system_status': sensors})
@tracer.wrap(name='sensor-simulator')
def simulate_all_sensors():
sensors = Sensor.query.all()
for sensor in sensors:
sensor.value = random.randint(1,100)
db.session.add_all(sensors)
db.session.commit()
return [s.serialize() for s in sensors]