added rest-API, sqlalchemy and nice structure

This commit is contained in:
2019-03-06 16:36:57 +01:00
commit 38ab1578b0
9 changed files with 422 additions and 0 deletions

28
api/__init__.py Normal file
View File

@@ -0,0 +1,28 @@
# -*- coding: utf-8 -*-
from flask import Blueprint
from flask_restplus import Api
api_authorizations = {
'apikey': {
'type': 'apiKey',
'in': 'header',
'name': 'X-API-KEY'
},
'basicAuth': {
'type': 'basic',
'scheme': 'basic'
},
'bearerAuth': {
'type': 'apiKey',
'scheme': 'bearer',
'name': 'Authorization',
'in': 'header'
}
}
api_bp = Blueprint('api', __name__, url_prefix='/api')
api_v1 = Api(api_bp, prefix="/v1", version='0.1', title='Vue Test API',
description='The Vue Test API', doc='/v1/doc/', authorizations=api_authorizations, security='bearerAuth')
from .example_api import *

118
api/example_api.py Normal file
View File

@@ -0,0 +1,118 @@
import logging
from random import *
from flask import jsonify, Blueprint
from flask_restplus import Resource, reqparse
from backend import basic_auth
from backend.api import api_v1, api_bp
@api_bp.route('/random')
def random_number():
"""
:return: a random number
"""
response = {
'randomNumber': randint(1, 100)
}
return jsonify(response)
class HelloWorld(Resource):
"""
This is a test class.
"""
def get(self):
"""
just a test!
:return: Hello: World
"""
print(str(self))
return {'hello': 'world'}
api_v1.add_resource(HelloWorld, '/')
class SensorData_Handler(Resource):
parser = reqparse.RequestParser()
parser.add_argument('values', type=str, required=True, help="sensor data values are required (as JSON list)")
@basic_auth.login_required
def get(self, mac):
sensor = Sensor.get_by_mac_user(mac, g.user)
if not sensor:
return "sensor not found", 404
return jsonify(sensor.get_sensor_data())
# return {'task': 'id: ' + mac}
@multi_auth.login_required
def post(self, mac):
sensor = Sensor.get_by_mac(mac)
if not sensor:
return "sensor not found", 404
print("JSON")
print(request.json)
print(request.json['values'])
args = SensorData_Handler.parser.parse_args()
print("values...")
print(args['values'])
values = json.loads(args['values'])
wasss_app.logger.info("vals: " + str(values) + " (len: " + str(len(values)) + ")")
rough_geo_location = None
try:
rough_geo_location_info = None
ip = ipaddress.ip_address(request.remote_addr)
if request.remote_addr == "127.0.0.1":
ip = ipaddress.ip_address("89.245.37.108")
if isinstance(ip, ipaddress.IPv4Address):
rough_geo_location_info = geoip4.record_by_addr(str(ip))
elif isinstance(ip, ipaddress.IPv6Address):
rough_geo_location_info = geoip6.record_by_addr(str(ip))
if rough_geo_location_info is not None:
rough_geo_location = json.dumps({key: rough_geo_location_info[key] for key in ['country_code',
'country_name',
'postal_code',
'city',
'time_zone',
'latitude',
'longitude']
})
except ValueError:
pass
for values_at_time in values:
wasss_app.logger.info("values_at_time: " + str(values_at_time) + " (len: " + str(len(values_at_time)) + ")")
sensor_data = SensorData(sensor=sensor, rough_geo_location=rough_geo_location)
val_cycle = cycle(values_at_time)
for sensor_data_header in sensor.get_sensor_data_headers():
value = next(val_cycle)
if sensor_data_header == SensorData.HEADER_TIMESTAMP:
sensor_data.timestamp = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S%z")
wasss_app.logger.info(sensor_data.timestamp)
elif sensor_data_header == SensorData.HEADER_VOLTAGE:
sensor_data.voltage = value
elif sensor_data_header == SensorData.HEADER_TEMPERATURE:
sensor_data.temp = value
elif sensor_data_header == SensorData.HEADER_HUMIDITY:
sensor_data.humidity = value
elif sensor_data_header == SensorData.HEADER_PRESSURE:
sensor_data.pressure = value
elif sensor_data_header == SensorData.HEADER_BRIGHTNESS:
sensor_data.brightness = value
elif sensor_data_header == SensorData.HEADER_SPEED:
sensor_data.speed = value
elif sensor_data_header == SensorData.HEADER_MOTION:
sensor_data.motion = value
else:
gen_sen_data = GenericSensorData(sensor=sensor, name=sensor_data_header, value=value)
db.session.add(sensor_data)
db.session.commit()
return jsonify("ok")
api_v1.add_resource(SensorData_Handler, '/sensor/<string:mac>/data')