def setUp(self): """Set up a User and a new Trip""" self.user = User(username="******", password="******", email="*****@*****.**", first_name="john", last_name="smith", guest=False) db.session.add(self.user) db.session.commit() self.trip = Trip(start_date_time=datetime(2020, 4, 8, 10, 00), end_date_time=datetime(2020, 4, 10, 15, 00), number_of_people=3, name="TestTrip", user_id=self.user.id) db.session.add(self.trip) db.session.commit() tm1 = TripMeal(trip_id=self.trip.id, meal_id=1) tm2 = TripMeal(trip_id=self.trip.id, meal_id=1) tm3 = TripMeal(trip_id=self.trip.id, meal_id=2) tm4 = TripMeal(trip_id=self.trip.id, meal_id=2) tm5 = TripMeal(trip_id=self.trip.id, meal_id=2) tm6 = TripMeal(trip_id=self.trip.id, meal_id=3) tm7 = TripMeal(trip_id=self.trip.id, meal_id=3) db.session.add_all([tm1, tm2, tm3, tm4, tm5, tm6, tm7]) db.session.commit()
def create_trip(): data = request.get_json() or {} if 'title' not in data: return bad_request('must include title field') data['user_id'] = g.current_user.id trip = Trip() trip.from_dict(data) db.session.add(trip) db.session.commit() response = jsonify(trip.to_dict()) response.status_code = 201 response.headers['Location'] = url_for('api.get_trip', id=trip.id) return response
def add_trip(): """ add a new user trip """ data = request.get_json() try: # add new trip new_trip = Trip(name=data['name'], user_id=g.user.id, start_date=datetime.strptime(data['start_date'], '%Y-%m-%d'), end_date=datetime.strptime(data['end_date'], '%Y-%m-%d')) db.session.add(new_trip) db.session.commit() geolocator = Nominatim(user_agent=_app.name) for loc in data['locations']: _loc = geolocator.geocode(loc) new_loc = Location(name=loc, lat=_loc.latitude, lng=_loc.longitude, trip_id=new_trip.id) db.session.add(new_loc) db.session.commit() except OperationalError as e: db.session.rollback() return jsonify({"error": "something unexpected occurred!"}), 400 return jsonify({'data': "Trip added successfully."}), 201
def index(): form = AddTripForm() all_trips = current_user.trips trips_result = [] for trip in all_trips: flights = Flight.query.filter_by(trip_id=trip.id).all() stays = Stay.query.filter_by(trip_id=trip.id).all() events = Event.query.filter_by(trip_id=trip.id).all() trip_start_date = get_cal_start_date(flights, stays, events, iso_format=False) trip_obj = { 'id': trip.id, 'title': trip.title, 'num_travelers': len(trip.travelers), 'num_events': len(events), 'num_stays': len(stays), 'num_flights': len(flights), 'start_date': trip_start_date.strftime('%B %Y') } trips_result.append(trip_obj) if form.validate_on_submit(): trip = Trip(title=form.title.data) trip.travelers.append(current_user) db.session.add(trip) db.session.commit() flash('Your trip has been added!') return redirect(url_for('main.trip_view', id=trip.id)) return render_template('trips.html', trips=current_user.trips, form=form, trips_result=trips_result)
def setUp(self): """Set up a User and a new Trip and base meals""" self.client = app.test_client() with self.client as c: with c.session_transaction() as session: session['test'] = 1 with app.test_request_context(): self.user = User.register(username="******", password="******", email="*****@*****.**", first_name="john", last_name="smith", guest=False) db.session.add(self.user) db.session.commit() self.trip = Trip( start_date_time=datetime(2020, 4, 8, 10, 00), end_date_time=datetime(2020, 4, 9, 15, 00), number_of_people=3, name="TestTrip", user_id=self.user.id) db.session.add(self.trip) db.session.commit()
def new(req): if req.method == 'POST': form = TripForm(req.POST) print(form.is_valid()) if form.is_valid(): a = Trip(destination=form.cleaned_data['destination'], date=form.cleaned_data['date'], cost=form.cleaned_data['cost'], travel_agency=form.cleaned_data['travel_agency'], num_travellers=form.cleaned_data['num_travellers']) a.save() return redirect('app:trips') else: return render(req, 'new.html', {'form': form}) else: form = TripForm() return render(req, 'new.html', {'form': form})
def create_trip(user_id): user = User.query.get_or_404(user_id) data = request.get_json(silent=True) or {} if 'destination_address' not in data or 'destination_latitude' not in data or 'destination_longitude' not in data: return bad_request('Error. Trip was not created. Please try again.') existing_trips = user.trips.all() # Cannot create more than one trip at a time. for element in existing_trips: if element.is_tracking: return bad_request( 'A Trip is already underway. Cannot create another Trip.') trip = Trip() trip.from_dictionary(data, user_id) db.session.add(trip) db.session.commit() response = jsonify(trip.to_dictionary()) response.status_code = 201 return response
def post_trip(): data = request.get_json(force=True) trip = Trip( user_id=data['userId'], title=data['title'], start_date=data['startDate'], end_date=data['endDate'], start_lat=data['startLat'], start_lon=data['startLon'], end_lat=data['endLat'], end_lon=data['endLon'], route=data['route'], private=data['shared']) db.session.add(trip) db.session.commit() trip_json = jsonify({'payload': {'trip': trip.to_dict()}}) return trip_json
def seed_trips(): fishing = Trip(user_id=1, name='Fishing Trip', car_id=1, start_iso="2020-12-17T10:54:00-06:00", start_location="Nashville, TN", end_iso="2020-12-18T10:54:00-06:00", end_location="Austin, TX", directions="null") family = Trip(user_id=1, name='Family Trip', car_id=1, start_iso="2020-11-23T10:54:00-05:00", start_location="New York, NY", end_iso="2020-11-24T10:54:00-05:00", end_location="Chelsea, MI", directions="null") girls = Trip(user_id=1, name='Girls Trip', car_id=1, start_iso="2020-12-01T10:54:00-05:00", start_location="322 W 101st St, NY, NY", end_iso="2020-12-18T10:54:00-05:00", end_location="Charleston, SC", directions="null") camping = Trip(user_id=1, name='Camping Trip', car_id=1, start_iso="2020-09-17T10:54:00-05:00", start_location="New York, NY", end_iso="2020-09-17T15:54:00-08:00", end_location="Ontario, CA", directions="null") db.session.add(fishing) db.session.add(family) db.session.add(girls) db.session.add(camping) # db.session.add(5) db.session.commit()
def new_trip(): form = CreateTripForm() if form.validate_on_submit(): trip = Trip(location=form.location.data, user_id=current_user.id, details=form.details.data) db.session.add(trip) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('home')) return render_template('new_trip.html', form=form, title='New Trip')
def create_trip(): data=request.get_json() print(data) try: assert Company.query.filter(Company.id==data['company_id']).first().user_id==current_user.id t=Trip(company_id=data['company_id'], route_id=data['route_id']) db.session.add(t) db.session.commit() res={"tripid":t.id,"routeid":t.route_id} return make_response(jsonify(res), 200) except AssertionError: return make_response('Nu aveti permisiunile necesare', 403)
def create_trip(): form = TripForm() if form.validate_on_submit(): trip = Trip(title=form.title.data, destination=form.destination.data, user_id=current_user.id) db.session.add(trip) db.session.commit() flash('Congratulations, you successfully added a trip!', 'info') return redirect(url_for('trips')) return render_template('create-trip.html', title='Create a Trip', form=form)
def test_get_meal_numbers(self): """Check if correct number of meals are returned""" nums = self.trip.get_meal_numbers() self.assertEqual(nums['total_meals'], 7) self.assertEqual(nums['Breakfast'], 2) self.assertEqual(nums['Lunch'], 3) self.assertEqual(nums['Dinner'], 2) short_trip = Trip(start_date_time=datetime(2020, 4, 10, 10, 00), end_date_time=datetime(2020, 4, 11, 9, 00), number_of_people=3, name="short", user_id=self.user.id) db.session.add(short_trip) db.session.commit() nums = short_trip.get_meal_numbers() self.assertEqual(nums['total_meals'], 3)
def seed_trips(): simon = User.query.filter(User.username == 'simon').first() daphne = User.query.filter(User.username == 'daphne').first() yellowstone = Trip(title='Yellowstone and Back Again', user=simon, start_date='2020-08-09', end_date=None, start_lat=40.712776, start_lon=-74.005974, end_lat=45.045200, end_lon=-110.521767, private=False) grand_canyon = Trip(title='Grand Canyon Birthday', user=daphne, start_date=' 2020-09-27', end_date=None, start_lat=37.769893, start_lon=-122.421123, end_lat=36.106964, end_lon=-112.112999, private=False) route66 = Trip(title='Haunted Route 66', user=simon, start_date='2020-04-14', end_date=None, start_lat=40.712776, start_lon=-74.005974, end_lat=35.0820877, end_lon=-106.9566669, private=True) db.session.add(yellowstone) db.session.add(grand_canyon) db.session.add(route66) db.session.commit()
def create_trip(): ## Create form object form = TripForm() ## Form Processing if form.validate_on_submit(): ## Create Trip object trip = Trip(tripname=form.tripname.data, destination=form.destination.data, user_id=current_user.id, friend_id=form.friend_id.data) print(form.friend_id.data) ## Write Trip object to database db.session.add(trip) db.session.commit() ## Redirect to index page return redirect(url_for('index')) ## Render page and form return render_template('create_trip.html', form=form)
def newtrip(): form = NewTripForm() if form.validate_on_submit(): if form.picture.data is not None: filename = secure_filename(form.picture.data.filename) form.picture.data.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) newtrip = Trip(location = form.location.data, transport= form.transport.data, min_people= int(form.min_people.data), max_people= int(form.max_people.data), about= form.about.data, date = form.date.data, total_cost = int(form.total_cost.data), creator_id = current_user.id, trip_picture = filename) db.session.add(newtrip) db.session.commit() return redirect(url_for('home')) return render_template('newTrip.html', title='New Trip', form=form)
def setUp(self): """Set up a User and a new Trip""" self.user = User(username="******", password="******", email="*****@*****.**", first_name="john", last_name="smith", guest=False) db.session.add(self.user) db.session.commit() self.trip = Trip(start_date_time=datetime(2020, 4, 8, 10, 00), end_date_time=datetime(2020, 4, 9, 15, 00), number_of_people=3, name="TestTrip", user_id=self.user.id) db.session.add(self.trip) db.session.commit()
def trips(): form = TripForm() if form.validate_on_submit(): trip = Trip(title=form.title.data, author=current_user) db.session.add(trip) db.session.commit() flash(_('Your trip is created!')) return redirect(url_for('main.trips')) page = request.args.get('page', 1, type=int) trips = Trip.query.order_by(Trip.timestamp.desc()).paginate( page, current_app.config['TRIPS_PER_PAGE'], False) next_url = url_for('main.trips', page=trips.next_num) \ if trips.has_next else None prev_url = url_for('main.trips', page=trips.prev_num) \ if trips.has_prev else None return render_template('trips.html', title=_('Trips'), form=form, trips=trips.items, next_url=next_url, prev_url=prev_url)
class TripMealTests(TestCase): def setUp(self): """Set up a User and a new Trip""" self.user = User(username="******", password="******", email="*****@*****.**", first_name="john", last_name="smith", guest=False) db.session.add(self.user) db.session.commit() self.trip = Trip(start_date_time=datetime(2020, 4, 8, 10, 00), end_date_time=datetime(2020, 4, 10, 15, 00), number_of_people=3, name="TestTrip", user_id=self.user.id) db.session.add(self.trip) db.session.commit() tm1 = TripMeal(trip_id=self.trip.id, meal_id=1) tm2 = TripMeal(trip_id=self.trip.id, meal_id=1) tm3 = TripMeal(trip_id=self.trip.id, meal_id=2) tm4 = TripMeal(trip_id=self.trip.id, meal_id=2) tm5 = TripMeal(trip_id=self.trip.id, meal_id=2) tm6 = TripMeal(trip_id=self.trip.id, meal_id=3) tm7 = TripMeal(trip_id=self.trip.id, meal_id=3) db.session.add_all([tm1, tm2, tm3, tm4, tm5, tm6, tm7]) db.session.commit() def tearDown(self): TripMeal.query.delete() Trip.query.delete() User.query.delete() db.session.commit() def test_get_bc_days(self): """Check if correct number of days are returned""" self.assertEqual(self.trip.get_bc_days(), 1) def test_get_meal_numbers(self): """Check if correct number of meals are returned""" nums = self.trip.get_meal_numbers() self.assertEqual(nums['total_meals'], 7) self.assertEqual(nums['Breakfast'], 2) self.assertEqual(nums['Lunch'], 3) self.assertEqual(nums['Dinner'], 2) short_trip = Trip(start_date_time=datetime(2020, 4, 10, 10, 00), end_date_time=datetime(2020, 4, 11, 9, 00), number_of_people=3, name="short", user_id=self.user.id) db.session.add(short_trip) db.session.commit() nums = short_trip.get_meal_numbers() self.assertEqual(nums['total_meals'], 3) def test_get_total_ingredient_weights(self): """Check if ingredients weghts are totaled correctly""" weights = self.trip.get_total_ingredient_weights() self.assertEqual(weights['OATS'], 1428.84) self.assertEqual(weights['PINTO BEANS'], 476.28) self.assertEqual(weights['BROWN SUGAR'], 238.14) def test_get_total_food_weight(self): """Check it total food weight in lbs is given correctly""" total = self.trip.get_total_food_weight() self.assertEqual(total, 14.67) def test_get_ingredient_weights(self): """Check if the meal weight is distributed to ingredients in the correct proportions""" meal = Meal.query.get(1) w = meal.get_ingredient_weights() self.assertEqual(w['OATS'], 238.14) self.assertEqual(w['RAISINS'], 39.69) self.assertEqual(w['BROWN SUGAR'], 39.69) def test_get_total_nutrition_data(self): """Check if the nutrition data per meal is correct""" meal = Meal.query.get(1) n = meal.get_total_nutrition_data() self.assertEqual(n['fiber'], 25.79) self.assertEqual(n['fat'], 14.88) self.assertEqual(n['calories'], 1144.26) self.assertEqual(n['sodium'], 0)
def sms_reply(): text = request.values.get('Body', None) print("Number from: ") print(str(request.values.get('From', None))) resp = MessagingResponse() global cars global carsinfo global carconfirmed global myrental global startingmileage global priceperkm global startlat global startlon if carconfirmed == 0 and "rent" in text.lower() and "car" in text.lower(): cars = [] carsinfo = [] global access vehicle_ids = smartcar.get_vehicle_ids( access['access_token'])['vehicles'] for v in vehicle_ids: c = 1 vehicle = smartcar.Vehicle(v, access['access_token']) dist = calc_distance(userlat, userlong, vehicle.location()["data"]["latitude"], vehicle.location()["data"]["longitude"]) print("location: \n") print(vehicle.location()) print("Distance: \n\n") print(dist) if dist < 15: cars.append(vehicle) vinfo = vehicle.info() info = "Car " + str(c) + ": " + str(vinfo["year"]) + " " + str( vinfo["make"]) + " " + str(vinfo["model"]) info += ", " + str(dist)[0:4] + " km away" carsinfo.append(info) c += 1 response = "Ok, here are all the rental cars available within a 15-km radius:\n" for s in carsinfo: response += s + "\n" response += "\nTo see more about a car, respond with 'Car <number>'" resp.message(response) elif carconfirmed == 0 and "car" in text.lower(): carnum = int(text.replace("Car ", "")) print("Carnum = " + str(carnum)) print("len(cars) = " + str(len(carsinfo))) if carnum > len(cars): resp.message("That's not a valid Car number!") else: vehicle = cars[carnum - 1] response = "Ok, here's some information about Car " + str( carnum) + ":\n" vinfo = vehicle.info() response += str(vinfo["year"]) + " " + str( vinfo["make"]) + " " + str(vinfo["model"]) + "\n" vodom = vehicle.odometer() response += "Mileage: " + str(int( vodom["data"]["distance"])) + " km\n" response += "Pricing: $" + str(priceperkm)[0:4] + "/km\n" vloc = vehicle.location() startlat = vloc["data"]["latitude"] startlon = vloc["data"]["longitude"] response += "Location: https://www.google.com/maps/place/" + str( vloc["data"]["latitude"]) + "+" + str( vloc["data"]["longitude"]) + "/ \n\n" response += "To confirm this car rental, respond with 'Confirm'\n(note that confirming will unlock the car)" resp.message(response) myrental = vehicle carconfirmed = 1 elif carconfirmed == 1 and "confirm" in text.lower(): # myrental.unlock() startingmileage = myrental.odometer()["data"]["distance"] response = "Ok, your rental has been confirmed! Your rental car has been unlocked.\nRespond with 'Done' when you are finished." resp.message(response) elif carconfirmed == 1 and "Done" in text: # myrental.lock() distancetravelled = myrental.odometer( )["data"]["distance"] - startingmileage print("distancetravelled:\n") print(distancetravelled) response = "Ok, your rental has been locked!\nTotal distance travelled: " + str( int(distancetravelled)) + " km\n" response += "Total cost of trip: $" + str( int(distancetravelled / priceperkm))[0:4] response += "\nThank you for using SwiftLift" resp.message(response) vloc = myrental.location() vinfo = myrental.info() users = User.query.all() user = None print("here are the users: ") print(User.query.all()) for u in users: print(u.phonenumber) if u.phonenumber == request.values.get('From', None): user = u dt = datetime.datetime.now() minute = str(dt.minute) if dt.minute < 10: minute = "0" + str(dt.minute) time = str(dt.hour) + ":" + minute + ", " + str(dt.month) + "/" + str( dt.day) + "/" + str(dt.year) trip = Trip(startlat=str(startlat), startlon=str(startlon), endlat=str(vloc["data"]["latitude"]), endlon=str(vloc["data"]["longitude"]), distance=str(distancetravelled) + " km", car=str(vinfo["year"]) + " " + str(vinfo["make"]) + " " + str(vinfo["model"]), cost="$" + str(int(distancetravelled / priceperkm))[0:4], time=time, rider=user) db.session.add(trip) db.session.commit() carconfirmed = 0 else: resp.message("Sorry, I didn't get that.") return str(resp)
def new_trip(): form = CreateTripForm() if form.validate_on_submit(): if form.starting_at.data < (datetime.today() + timedelta(days=3)): flash('Izlet može početi najranije za 3 dana.', 'danger') return redirect(url_for('trips.new_trip')) if form.is_private.data: hashed_password = bcrypt.generate_password_hash( form.trip_password.data).decode('utf-8') picture_file = 'trip_default.jpg' if form.trip_picture.data: picture_file = save_picture_trip(form.trip_picture.data) trip = Trip(name=form.name.data, location=form.location.data, user_id=current_user.id, price=form.price.data, people_number=form.people_number.data, starting_at=form.starting_at.data, transport_type=form.transport_type.data, trip_duration=form.trip_duration.data, is_private=form.is_private.data, trip_password=hashed_password, details=form.details.data, image_file=picture_file) else: picture_file = 'trip_default.jpg' if form.trip_picture.data: picture_file = save_picture_trip(form.trip_picture.data) trip = Trip(name=form.name.data, location=form.location.data, user_id=current_user.id, price=form.price.data, people_number=form.people_number.data, starting_at=form.starting_at.data, transport_type=form.transport_type.data, trip_duration=form.trip_duration.data, is_private=form.is_private.data, details=form.details.data, image_file=picture_file) try: db.session.add(trip) db.session.commit() trip = Trip.query.filter_by(name=form.name.data).first() event = Event(name=form.name.data, event="is_full", trip_id=trip.id) event2 = Event(name=form.name.data, event="starting_soon", trip_id=trip.id) event3 = Event(name=form.name.data, event="trip_deleted", trip_id=trip.id) db.session.add(event) db.session.add(event2) db.session.add(event3) db.session.commit() flash('Vaš izlet je uspješno stvoren!', 'success') return redirect(url_for('main.home')) except: flash( "Greška prilikom stvaranja izleta. Provjerite Vaš unos. Za korisniču podršku nam se obratite " "na email -- [email protected] -- .", "danger") return render_template('new_trip2.html', form=form, title='New Trip')
def get_trips(): page = request.args.get('page', 1, type=int) per_page = min(request.args.get('per_page', 10, type=int), 100) data = Trip.to_collection_dict(Trip.query.order_by(Trip.timestamp.desc()), page, per_page, 'api.get_trips') return jsonify(data)
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