def put_stop(stop_id): data = request.json try: stop = Stop.query.get(stop_id) for key in data: if key == 'cuisines': for cuisine in data['cuisines']: c = Cuisine.query.filter(Cuisine.name == cuisine).first() if isinstance(c, Cuisine): stop.cuisines.append(c) else: cuisine_type = Cuisine(name=cuisine) stop.cuisines.append(cuisine_type) else: stop[snake_case(key)] = data[key] db.session.commit() return {'stops': normalize(stop.to_dict())} except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) db.session.rollback() return {'errors': ['An error occurred while retrieving the data']}, 500
def get_hotel(stop_id): hotel = Hotel.query.\ filter(Hotel.id == Stop.hotel_id).\ filter(Stop.id == stop_id).first() if not hotel: return {}, 404 hotel_json = jsonify({'hotels': normalize(hotel)}) return restaurant_json
def get_car(car_id): try: car = Car.query.filter(Car.id == car_id).first() car_json = jsonify({'cars': normalize(car.to_dict())}) return car_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while retrieving the data']}, 500
def get_gas_station(stop_id): gas_station = GasStation.query.\ filter(GasStation.id == Stop.gas_station_id).\ filter(Stop.id == stop_id).first() if not gas_station: return {}, 404 gas_station_json = jsonify( {'gasStations': normalize(gas_station.to_dict())}) return gas_station_json
def get_cars(user_id): try: cars = Car.query.filter(Car.user_id == user_id).all() car_dicts = [car.to_dict() for car in cars] car_json = jsonify({'cars': normalize(car_dicts)}) return car_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while retrieving the data']}, 500
def get_trip(trip_id): try: trip = Trip.query.filter(Trip.id == trip_id).first() trip_json = jsonify({'payload': {'trips': normalize(trip.to_dict())}}) return trip_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while retrieving the data']}, 500
def get_cuisine(stop_id): try: cuisine = Cuisine.query.\ filter(Cuisine.id == Stop.cuisine_id).\ filter(Stop.id == stop_id).first() cuisine_json = jsonify({'cuisines': normalize(cuisine)}) return restaurant_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while retrieving the data']}, 500
def get_trips(user_id): try: trips = Trip.query.filter(Trip.user_id == user_id).all() trip_dicts = [trip.to_dict() for trip in trips] trips_json = jsonify({'payload': {'trips': normalize(trip_dicts)}}) return trips_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while retrieving the data']}, 500
def modify_trip(trip_id): data = request.json # Amend the Trip Model with attributes sent from Frontend for the DB trip = Trip.query.get(trip_id) for key, value in data['db'].items(): setattr(trip, snake_case(key), value) # Query for the Trip's car car = Car.query.get(data['db']['carId']) # Recreate an instance of the Trip Algorithm trip_algo = TripClass(startCor=coords_from_str(trip.start_location), endCor=coords_from_str(trip.end_location), travelPerDay=data['db']['dailyTimeLimit'], travelPerIncrement=data['db']['stopTimeLimit'], milesToRefuel=car.miles_to_refuel, avoidTolls=data['db']['avoidTolls']) # Recreate the directions of the Algorithm trip_algo.constructFromDirections(trip.directions) # Get preferences and search next stop for places that match preferences # food_query, hotel, gas = get_preferences(data['preferences']) suggestions = trip_algo.getNextStopDetails( foodQuery=data['preferences']['foodQuery'][0], hotel=data.get('hotel'), gas=data.get('gas')) # Adjust the directions and save to the database model directions = trip_algo.getDirections() trip.directions = directions try: db.session.commit() trip_json = jsonify({ 'payload': { 'trips': normalize(trip.to_dict()), 'currentId': trip.id }, 'suggestions': { 'suggestions': suggestions }, 'timeline': trip.get_timeline() }) return trip_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) db.session.rollback() return {'errors': ['An error occurred while retrieving the data']}, 500
def post_cuisine(): data = request.data try: cuisine = cuisine( name=data.name, place_id=data.placeId) db.session.add(cuisine) db.session.commit() return {'cuisines': normalize(cuisine)} except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while retrieving the data']}, 500
def post_car(user_id): data = request.json car = Car(user_id=user_id, api_id=data['apiId'], make=data['make'], model=data['model'], year=data['year'], mpg=data['mpg'], miles_to_refuel=int(data['mpg']) * int(data['tankSize'])) try: db.session.add(car) db.session.commit() car_json = jsonify({'cars': normalize(car.to_dict())}) return car_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) db.session.rollback() return {'errors': ['An error occurred while creating data']}, 500
def post_gas_station(): data = request.json try: gas_station = GasStation(name=data['name'], phone_num=data['phoneNum'], street_address=data['streetAddress'], city=data['city'], state=data['state'], zip_code=data['zipCode'], img_url=data['imgUrl'], place_id=data['placeId']) db.session.add(gas_station) db.session.commit() return {'gasStations': normalize(gas_station.to_dict())} except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) return {'errors': ['An error occurred while retrieving the data']}, 500
def get_gas_stations(): gas_stations = GasStation.query.all() if not gas_stations: return {}, 404 gas_list = [gas_station.to_dict() for gas_station in gas_stations] return {'gasStations': normalize(gas_list)}
def get_hotels(): hotels = Hotel.query.all() if not hotels: return {}, 404 hotel_list = [hotel.to_dict() for hotel in hotels] return {'hotels': normalize(hotel_list)}
def get_stops(trip_id): stops = Stop.query.filter(Stop.trip_id == trip_id).all() if stops: return {'payload': normalize([stop.to_dict() for stop in stops])} else: return {}, 404
def post_trip(user_id): req = request.json data = req['db'] # User's food preferences food_query = req['preferences']['foodQuery'] # Convert miles to meters for distance per tank of selected car fuel_distance = round(data['milesToRefuel'] * 1609.34) origin = data['startLocation'] destination = data['endLocation'] print('***\n\nEnd Time: ', data['endTimeForDay'], '\n\n***') print('***\n\nEnd Time: ', data['dailyStartTime'], '\n\n***') # Create an instance of the trip algorithm and generate a new trip trip_algo = TripClass() directions_json = trip_algo.createNewTrip( start=origin, end=destination, metersToRefuel=fuel_distance, timeBetweenStops=int(data['timeBetweenStops']), endTimeForDay=data['endTimeForDay'], startISO=data['startISO'], # + '00:000Z', # ! No Timezone avoidTolls=data['avoidTolls'], dailyStartTime=data['dailyStartTime']) # Create a model of the Trip for the DB trip = Trip(user_id=data['userId'], name=f'{origin} -> {destination}', car_id=data['carId'], directions=directions_json, start_location=origin, end_location=destination, start_iso=data['startISO']) # hotel_needed = True if data['endTimeForDay'] else False next_stop_suggestions = trip_algo.getNextStopDetails( foodQuery=food_query[0], ) try: db.session.add(trip) db.session.commit() # Create a json object structured for Redux slices of state trip_json = jsonify({ 'payload': { 'trips': normalize(trip.to_dict()), 'currentTripId': trip.id }, 'suggestions': next_stop_suggestions, 'directions': { 'itinerary': trip.directions, 'foodQuery': food_query, 'avoidTolls': data['avoidTolls'] } }) return trip_json except SQLAlchemyError as e: error = str(e.__dict__['orig']) print(error) db.session.rollback() return {'errors': ['An error occurred while retrieving the data']}, 500
def get_stop(stop_id): stop = Stop.query.get(stop_id) if stop: return {'payload': normalize(stop.to_dict())} else: return {}, 404