rollerverbrauch/app/routes/filling_stations.py

62 lines
2.1 KiB
Python

from flask import request, jsonify
from flask_security import login_required
from flask_security.core import current_user
import requests
from ..entities import FillingStation
from .. import app, db
@app.route('/filling_stations/favourites/toggle/<fsid>')
def add_favourite_filling_stations(fsid):
favourite_ids = {x.id: x for x in current_user.favourite_filling_stations}
if fsid in favourite_ids:
current_user.favourite_filling_stations.remove(favourite_ids[fsid])
state = 'normal'
else:
fs = FillingStation.query.filter(FillingStation.id == fsid).first()
current_user.favourite_filling_stations.append(fs)
state = 'favourite'
db.session.commit()
return jsonify({'state': state})
@app.route('/filling_stations', methods=['GET'])
@login_required
def query_filling_stations():
api_key = app.config['TANKERKOENIG_API_KEY']
latitude = request.args.get('latitude')
longitude = request.args.get('longitude')
radius = request.args.get('radius', default=1.5)
gas_type = request.args.get('type', default='all')
sort = request.args.get('sort', default='dist')
url = 'https://creativecommons.tankerkoenig.de/json/list.php'
params = {
'lat': latitude, 'lng': longitude, 'rad': radius, 'apikey': api_key, 'type': gas_type, 'sort': sort
}
response = requests.get(url, params=params)
data = response.json()
for station in data['stations']:
fs = FillingStation.query.filter(FillingStation.id == station['id']).first()
if not fs:
fs = FillingStation()
fs.id = station['id']
fs.brand = station['brand']
fs.lat = station['lat']
fs.lng = station['lng']
fs.name = station['name']
fs.street = station['street']
fs.place = station['place']
fs.houseNumber = station['houseNumber']
fs.postCode = station['postCode']
db.session.add(fs)
if fs in current_user.favourite_filling_stations:
station['state'] = 'favourite'
else:
station['state'] = 'normal'
db.session.commit()
return jsonify(data)