server/fgs/views.py

75 lines
2.3 KiB
Python
Raw Normal View History

2020-02-17 19:25:10 -08:00
from . import app, db
2020-02-01 14:29:56 -08:00
from .jwt import jwt_required
from .model import *
from flask import g, jsonify, request, abort
from sqlalchemy import func
2020-05-12 17:29:40 -07:00
import geopy.distance
2020-02-01 14:29:56 -08:00
@app.route('/')
def index():
return 'Hello, world!'
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
if username is None or password is None: abort(400)
user = User.query.filter_by(username=username).first()
if user is None or not user.check_password(password): abort(400)
return jsonify({ 'token': user.get_jwt().decode() })
@app.route('/me')
@jwt_required
def me():
return jsonify({ 'username' : g.user.username })
@app.route('/collars')
@jwt_required
def collars():
2020-02-17 19:25:10 -08:00
active_collars = []
for collar in Collar.query.filter_by(active=True).all():
max_point = DataPoint.query.filter_by(collar_id=collar.id).\
order_by(DataPoint.datetime.desc()).\
first()
active_collars.append(
{'id': collar.id, 'name': collar.name, 'pos':
{'longitude': max_point.longitude, 'latitude': max_point.latitude}}
)
2020-02-01 14:29:56 -08:00
return jsonify(active_collars)
2020-05-12 17:29:40 -07:00
@app.route('/collars/stats/distance')
@jwt_required
def collars_distance():
active_collars = []
for collar in Collar.query.filter_by(active=True).all():
coords = DataPoint.query.filter_by(collar_id=collar.id).\
order_by(DataPoint.datetime.desc())
distance_kilometers = 0
coords_pairs = list(map(lambda e : (e.longitude, e.latitude), coords))
coord_last = coords_pairs.pop()
for coord in coords_pairs:
distance_kilometers += geopy.distance.VincentyDistance(coord_last,coord).km
coord_last = coord
active_collars.append(
{'id': collar.id, 'name': collar.name,
'distance': distance_kilometers }
)
return jsonify(active_collars)
2020-02-01 14:29:56 -08:00
@app.route('/collars/<int:id>/history')
@jwt_required
def collar_history(id):
collar = Collar.query.filter_by(id=id).first()
if collar is None: abort(404)
data_points = DataPoint.query.\
filter_by(collar_id=id).\
order_by(DataPoint.datetime.desc()).\
all()
return jsonify([point.to_dict() for point in data_points])