from . import app from .jwt import jwt_required from .model import * from flask import g, jsonify, request, abort from sqlalchemy import func @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(): active_collars = Collar.query.\ filter_by(active=True).\ join(DataPoint, isouter=True).\ order_by(DataPoint.datetime.desc()).\ group_by(Collar.id).\ with_entities( Collar.id, Collar.name, DataPoint.longitude, DataPoint.latitude).\ all() active_collars = [ {'id': id, 'name': name, 'pos': {'longitude': lo, 'latitude': la}} for (id, name, lo, la) in active_collars] return jsonify(active_collars) @app.route('/collars//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])