def post(self, current_user): """offers a new ride""" data = request.json origin = data['origin'] destination = data['destination'] date = data['date'] ride = Ride(origin=origin, destination=destination, date=date) try: all_rides = ride.fetch_all() for this_ride in all_rides: if this_ride['origin'] == ride.origin and this_ride[ 'destination'] == ride.destination and this_ride[ 'date'] == ride.date and this_ride[ 'driver'] == current_user[2]: response = { 'message': 'This ride already exists.', } return make_response(jsonify(response)), 202 driver = current_user[2] ride.insert(driver) response = { 'message': 'You offered a ride successfully.', } return make_response(jsonify(response)), 201 except Exception as e: response = {'message': str(e)} return make_response(jsonify(response)), 500
def test_follow_rides(self): # create four users u1 = User(username='******', email='*****@*****.**') u2 = User(username='******', email='*****@*****.**') u3 = User(username='******', email='*****@*****.**') u4 = User(username='******', email='*****@*****.**') db.session.add_all([u1, u2, u3, u4]) # create four rides now = datetime.utcnow() r1 = Ride(start="Eldoret", destination="Kakamega", time="06/01/2018 10:00 AM", seats=2, cost=200, driver=u1, timestamp=now + timedelta(seconds=1)) r2 = Ride(start="Nakuru", destination="Naivasha", time="06/01/2018 11:00 AM", seats=4, cost=100, driver=u2, timestamp=now + timedelta(seconds=4)) r3 = Ride(start="Nairobi", destination="Thika", time="06/01/2018 2:00 PM", seats=3, cost=50, driver=u3, timestamp=now + timedelta(seconds=3)) r4 = Ride(start="Narok", destination="Nairobi", time="06/01/2018 4:00 PM", seats=2, cost=80, driver=u4, timestamp=now + timedelta(seconds=2)) db.session.add_all([r1, r2, r3, r4]) db.session.commit() # setup the followers u1.follow(u2) # john follows susan u1.follow(u4) # john follows david u2.follow(u3) # susan follows mary u3.follow(u4) # mary follows david db.session.commit() # check the followed posts of each user f1 = u1.followed_rides().all() f2 = u2.followed_rides().all() f3 = u3.followed_rides().all() f4 = u4.followed_rides().all() self.assertEqual(f1, [r2, r4, r1]) self.assertEqual(f2, [r2, r3]) self.assertEqual(f3, [r3, r4]) self.assertEqual(f4, [r4])
def make_ride(student, bike): ride = Ride(rider=student, bike=bike, checkout_station=bike.location) payment = student.payments.filter(status="available")[0] payment.status = "out" if not payment.end_date: if payment.plan.name == "Day Plan": delta = datetime.timedelta(days=1) else: delta = datetime.timedelta(days=30) payment.end_date = datetime.datetime.now(pytz.utc) + delta bike.status = "out" payment.save() bike.save() ride.save()
def dashboard(): form = RideForm() if form.validate_on_submit(): ride = Ride(start=form.start.data, destination=form.destination.data, time=form.time.data, seats=form.seats.data, cost=form.cost.data, driver=current_user) db.session.add(ride) db.session.commit() flash('Your ride is now live!') return redirect(url_for('main.dashboard')) page = request.args.get('page', 1, type=int) rides = current_user.followed_rides().paginate( page, current_app.config['RIDES_PER_PAGE'], False) next_url = url_for('main.dashboard', page=rides.next_num) \ if rides.has_next else None prev_url = url_for('main.dashboard', page=rides.prev_num) \ if rides.has_prev else None return render_template('dashboard.html', title='Home', form=form, rides=rides.items, next_url=next_url, prev_url=prev_url)
def get(self, current_user, r_id): """Method for get requests""" if r_id: try: ride = Ride(id=r_id) ride = ride.find_by_id(r_id) if ride: return jsonify(ride), 200 return jsonify({'msg': "Ride not found "}), 404 except Exception as e: response = {'message': str(e)} return make_response(jsonify(response)), 500 else: try: ride = Ride() rides = ride.fetch_all() if rides == []: return jsonify( {"msg": " There are no rides rides at the moment"}), 200 return jsonify(rides), 200 except Exception as e: response = {'message': str(e)} return make_response(jsonify(response)), 500
def search(): if not g.search_form.validate(): return redirect(url_for('main.dashboard')) page = request.args.get('page', 1, type=int) rides, total = Ride.search(g.search_form.q.data, page, current_app.config['RIDES_PER_PAGE']) next_url = url_for('main.search', q=g.search_form.q.data, page=page + 1) \ if total > page * current_app.config['RIDES_PER_PAGE'] else None prev_url = url_for('main.search', q=g.search_form.q.data, page=page - 1) \ if page > 1 else None return render_template('search.html', title='Search', rides=rides, next_url=next_url, prev_url=prev_url)
def create_ride(): form = CreateRideForm() cars = Car.query.filter_by(owner_id=current_user.id).all() form.cars.choices = [(car.id, car.brand) for car in cars] if form.validate_on_submit(): language = guess_language(form.about_ride.data) if language == 'UNKNOWN' or len(language) > 5: language = '' ride = Ride(driver=current_user.id, car=form.cars.data, from_location=form.from_location.data, to_location=form.to_location.data, ride_time=form.ride_time.data, free_seats=form.free_seats.data, about_ride=form.about_ride.data, language=language) db.session.add(ride) db.session.commit() flash(_('Ride was created')) return redirect(url_for('ride.available_rides')) return render_template('ride/create_ride.html', form=form)
def sms(request): response = twilio.twiml.Response() fromNumber = request.POST.get("From") number = fromNumber[2:] lookup = number[0:3]+"-"+number[3:6]+"-"+number[6:] try: student = Student.objects.get(phone=lookup) except: duplicates = Student.objects.filter(phone=lookup) if len(duplicates) > 1: message = ("Multiple students have your number. Email [email protected] whether you're " + "{} or " * (len(duplicates)-1) + "{}.").format(*duplicates) email_razzi("Duplicates! {}".format(duplicates)) else: message = "Welcome to PennCycle! Visit app.penncycle.org to get started. Sign up for any plan to start checking bikes out by texting." response.sms(message) return response body = request.POST.get("Body", "").lower() if any(command in body for command in ["rent", "checkout", "check out", "check-out"]): if not student.can_ride: message = "Hi {}! ".format(student.name) currentRides = student.ride_set.filter(checkin_time=None) if len(currentRides) > 0: bike = currentRides[0].bike.bike_name message += "You can't check bikes out until you check bike {} back in. ".format(bike) if not student.waiver_signed: email_razzi("Waiver not signed by {}".format(student)) message += "You need to fill out a waiver. Go to app.penncycle.org/waiver to do so." response.sms(message) return response try: bike_number = re.search("\d+", body).group() except: response.sms("Command not understood. Text 'info' for a list of commands. Example of checking out a bike would be: Checkout 10") email_razzi("Looks like somebody had the wrong bike number. Message: {}".format(body)) return response try: bikes = Bike.objects.filter(status="available").filter(bike_name__startswith=bike_number) for b in bikes: if b.bike_name.split()[0] == bike_number: bike = b ride = Ride(rider=student, bike=bike, checkout_station=bike.location) student.payments.filter(status="available")[0].status = "out" ride.save() message = "You have successfully checked out bike {}. The combination is {}. To return the bike, reply 'checkin PSA' (or any other station). Text 'Stations' for a list.".format(bike_number, bike.combo) except: message = "The bike you have requested was unavailable or not found. Text 'Checkout (number)', where number is 1 or 2 digits." count = 0 bikes = Bike.objects.filter(status="available").filter(bike_name__startswith=bike_number) for b in bikes: if b.bike_name.split()[0] == bike_number: count += 1 email_razzi("Problem with bike {} and student {}. Message was {}. Found {} / {}".format(bike_number, student, body, count, len(bikes))) elif any(command in body for command in ["checkin", "return", "check in", "check-in"]): location = None stations = [station.name.lower() for station in Station.objects.all()] for station in stations: if station in body: if station == "psa": location = Station.objects.get(name="PSA") else: location = Station.objects.get(name=station.capitalize()) if not location: email_razzi("Station didn't match for checkin. Message was {}".format(body)) message = "Station not found. Options: PSA, Rodin, Ware, Fisher, Stouffer, Houston, Hill (PSA=Penn Student Agencies). To return a bike text 'Checkin PSA' or another station." response.sms(message) return response ride = student.ride_set.all().order_by("-id")[0] ride.checkin_time = datetime.datetime.now() ride.checkin_station = location ride.bike.status = "available" ride.save() message = "You have successfully returned your bike at {}. Make sure it is locked, and we will confirm the bike's checkin location shortly. Thanks!".format(location) email_razzi("{} successfully returned! Ride was {}".format(ride, ride.bike)) elif any(command in body for command in ["station", "stations", "location", "locations"]): message = "Stations: PSA, Rodin, Ware, Fisher, Stouffer, Houston, and Hill (PSA=Penn Student Agencies). To return a bike text 'Checkin PSA' or another station." else: if student.can_ride: message = "Hi, {}! Checkout a bike: 'Checkout (number)'. Checkin: 'Checkin (location)'. Text 'stations' to view stations. You're eligible to checkout bikes.".format(student.name) else: currentRides = student.ride_set.filter(checkin_time=None) if len(currentRides) > 0: bike = currentRides[0].bike.bike_name message = "Hi {}! You still have {} out. Until you check it in, you cannot check out bikes. Text 'locations' for checkin stations.".format(student.name, bike) elif not student.waiver_signed: email_razzi("Waiver not signed by {}".format(student)) message = "You need to fill out a waiver. Go to app.penncycle.org/waiver to do so." else: email_razzi("{} doesn't have any payments, it would seem. Contact him at {}".format(student.name, student.email)) message = "You are currently unable to check out bikes. Go to penncycle.org and enter your penncard to check your status." if not any(command in body for command in ["help", "info", "information", "?"]): email_razzi(body) response.sms(message) return response