diff --git a/flaskr/controllers/main_controller.py b/flaskr/controllers/main_controller.py index fd3984a..1fe2896 100644 --- a/flaskr/controllers/main_controller.py +++ b/flaskr/controllers/main_controller.py @@ -2,10 +2,14 @@ from flask import Blueprint, render_template, flash, request, redirect, url_for from flaskr.extensions import cache from flaskr.forms import LoginForm, EstimateForm -from flaskr.models import db, User, Estimation +from flaskr.models import db, User, Estimation, StatusEnum +from flaskr.geocoder import CachedGeocoder from flaskr.core import generate_unique_id +import sqlalchemy +import geopy + main = Blueprint('main', __name__) @@ -27,10 +31,10 @@ def estimate(): estimation.email = form.email.data estimation.first_name = form.first_name.data estimation.last_name = form.last_name.data - estimation.status = 'pending' - estimation.origin_addresses = form.origin_addresses - estimation.destination_addresses = form.destination_addresses - estimation.compute_optimal_destination = form.compute_optimal_destination + estimation.status = StatusEnum.pending + estimation.origin_addresses = form.origin_addresses.data + estimation.destination_addresses = form.destination_addresses.data + estimation.compute_optimal_destination = form.compute_optimal_destination.data db.session.add(estimation) db.session.commit() @@ -44,8 +48,58 @@ def estimate(): @main.route("/compute") def compute(): + + def _respond(_msg): + return "
%s" % _msg + + def _handle_failure(_estimation, _failure_message): + _estimation.status = StatusEnum.failed + db.session.commit() + response = "" - # TODO + try: + estimation = Estimation.query \ + .filter_by(status=StatusEnum.pending) \ + .order_by(Estimation.id.desc()) \ + .one() + except sqlalchemy.orm.exc.NoResultFound: + return _respond("No estimation in the queue.") + + response += u"Processing estimation `%s` of `%s`...\n" % (estimation.id, estimation.email) + + geocoder = CachedGeocoder() + + destinations_addresses = estimation.destination_addresses.split("\n") + destinations = [] + + for i in range(len(destinations_addresses)): + + destination_address = str(destinations_addresses[i]) + + try: + destination = geocoder.geocode(destination_address) + except geopy.exc.GeopyError as e: + response += u"Failed to geolocalize destination `%s`.\n%s" % ( + destination_address, e, + ) + _handle_failure(estimation, response) + return _respond(response) + + if destination is None: + response += u"Failed to geolocalize destination `%s`." % ( + destination_address, + ) + _handle_failure(estimation, response) + return _respond(response) + + destinations.append(destination) + + response += u"Destination: %s == %s (%f, %f)\n" % ( + destination_address, destination.address, + destination.latitude, destination.longitude, + ) + + - return response + return _respond(response) -- libgit2 0.21.2