Ejemplo n.º 1
0
def rides_list():
    """Show feed to passengers and drivers"""

    print request.form
    #getting information from form
    passenger_location = request.form.get('passenger_location')
    passenger_destination = request.form.get('passenger_destination')
    pick_up_time = request.form.get('pick_up_time')

    #if there is a passenger_id. Get the id.
    print session

    if 'passenger_id' in session:
        passenger_id = session['passenger_id']
        print passenger_id
        #creating row that has the passengers stored in database
        new_ride = Ride(passenger_location=passenger_location,
                        passenger_destination=passenger_destination,
                        pick_up_time=pick_up_time,
                        passenger_id=passenger_id)

        db.session.add(new_ride)
        #db.session.flush()
        db.session.commit()
        ride_return = str(new_ride.ride_id)
        print ride_return

        return ride_return

    return "failed"  #this line should never be reached
Ejemplo n.º 2
0
def writeDB(req):
    data = json.loads(req)
    if data["table"] == "User":
        # Add a new User
        if data["caller"] == "addUser":
            responseToReturn = Response()
            if checkHash(data["password"]):
                newUser = User(
                    username=data["username"], password=data["password"])
                session.add(newUser)
                session.commit()
                responseToReturn.status_code = 201
            else:
                responseToReturn.status_code = 400
            return (responseToReturn.text, responseToReturn.status_code)
        # Remove an existing User
        elif data["caller"] == "removeUser":
            session.query(User).filter_by(username=data["username"]).delete()
            session.query(Ride).filter_by(created_by=data["username"]).delete()
            session.commit()
            responseToReturn = Response()
            responseToReturn.status_code = 200
            return (responseToReturn.text, responseToReturn.status_code)

    elif data["table"] == "Ride":
        # Add a new Ride
        if data["caller"] == "createRide":
            source = int(data["source"])
            dest = int(data["destination"])
            responseToReturn = Response()
            noRows = 198
            if source in range(1, noRows + 1) and dest in range(1, noRows + 1):
                newRide = Ride(created_by=data["created_by"], username="", timestamp=data["timestamp"],
                               source=source, destination=dest)
                session.add(newRide)
                session.commit()
                responseToReturn.status_code = 201
            else:
                responseToReturn.status_code = 400
            return (responseToReturn.text, responseToReturn.status_code)

        elif data["caller"] == "joinRide":
            rideExists = session.query(Ride).filter_by(
                ride_id=data["rideId"]).first()
            if rideExists.username:
                rideExists.username += ", " + data["username"]
            else:
                rideExists.username += data["username"]
            session.commit()
            responseToReturn = Response()
            responseToReturn.status_code = 200
            return (responseToReturn.text, responseToReturn.status_code)

        elif data["caller"] == "deleteRide":
            session.query(Ride).filter_by(ride_id=data["rideId"]).delete()
            session.commit()
            responseToReturn = Response()
            responseToReturn.status_code = 200
            return (responseToReturn.text, responseToReturn.status_code)
Ejemplo n.º 3
0
def create_ride(driver_id, seats, date, start_loc, end_loc, price, comments):
    """Add a ride to the database."""
    new_ride = Ride(driver_id=driver_id,
                    seats=seats,
                    date=date,
                    start_loc=start_loc,
                    end_loc=end_loc,
                    price=price,
                    comments=comments)
    db.session.add(new_ride)
    db.session.commit()
    return new_ride
Ejemplo n.º 4
0
def actualSync(users_rides):
    '''
    Sync functionality. `users_rides` is [users, rides]
    '''
    global workerStatus
    workerStatus = "OLD"
    print("Users:\n")
    for users in users_rides[1]:
        print(users["username"], users["password"])
        newUser = User(username=users["username"], password=users["password"])
        session.add(newUser)
        session.commit()
    print("Rides:\n")
    for rides in users_rides[0]:
        print(rides["created_by"], rides["username"], rides["timestamp"],
              rides["source"], rides["destination"])
        newRide = Ride(created_by=rides["created_by"],
                       username=rides["username"],
                       timestamp=rides["timestamp"],
                       source=rides["source"],
                       destination=rides["destination"])
        session.add(newRide)
        session.commit()
Ejemplo n.º 5
0
    first_name = f'test{i}'
    last_name = f'test{i}'
    fake_user = User(first_name=first_name,
                     last_name=last_name,
                     password=password,
                     email=email,
                     phone_num='4088893883')
    db.session.add(fake_user)
    db.session.commit()
    #For each user create 10 fake rides
    for _ in range(10):
        start_loc = f'teststart{_}'
        end_loc = f'testend{_}'
        fake_rides = Ride(driver_id=fake_user.user_id,
                          seats=randint(1, 4),
                          date=fake.date_time_between_dates(
                              datetime_start=datetime(2020, 9, 1),
                              datetime_end=datetime(2021, 5, 1)),
                          start_loc=start_loc,
                          end_loc=end_loc,
                          price=randint(1, 10),
                          comments='n/a')
        db.session.add(fake_rides)
        db.session.commit()
    #For each ride, create 2 requests
    # fake_user_rides = Request(ride_id= fake_rides.ride_id, rider_id = fake_user.user_id)
    # fake_user_rides_2 = Request(ride_id= fake_rides.ride_id, rider_id = 1)
    # db.session.add(fake_user_rides)
    # db.session.add(fake_user_rides_2)
    # db.session.commit()
Ejemplo n.º 6
0
def writetoDB():
    data = request.get_json()
    if data["table"] == "User":
        # Add a new User
        if data["caller"] == "addUser":
            responseToReturn = Response()
            if checkHash(data["password"]):
                newUser = User(username=data["username"],
                               password=data["password"])
                db.session.add(newUser)
                db.session.commit()
                responseToReturn.status_code = 201
            else:
                responseToReturn.status_code = 400
            return (responseToReturn.text, responseToReturn.status_code,
                    responseToReturn.headers.items())
        # Remove an existing User
        elif data["caller"] == "removeUser":
            User.query.filter_by(username=data["username"]).delete()
            Ride.query.filter_by(created_by=data["username"]).delete()
            db.session.commit()
            responseToReturn = Response()
            responseToReturn.status_code = 200
            return (responseToReturn.text, responseToReturn.status_code,
                    responseToReturn.headers.items())

    elif data["table"] == "Ride":
        # Add a new Ride
        if data["caller"] == "createRide":
            source = int(data["source"])
            dest = int(data["destination"])
            responseToReturn = Response()
            if source in range(1, noRows + 1) and dest in range(1, noRows + 1):
                newRide = Ride(created_by=data["created_by"],
                               username="",
                               timestamp=data["timestamp"],
                               source=source,
                               destination=dest)
                db.session.add(newRide)
                db.session.commit()
                responseToReturn.status_code = 201
            else:
                responseToReturn.status_code = 400
            return (responseToReturn.text, responseToReturn.status_code,
                    responseToReturn.headers.items())

        elif data["caller"] == "joinRide":
            rideExists = Ride.query.filter_by(ride_id=data["rideId"]).first()
            if rideExists.username:
                rideExists.username += ", " + data["username"]
            else:
                rideExists.username += data["username"]
            db.session.commit()
            responseToReturn = Response()
            responseToReturn.status_code = 200
            return (responseToReturn.text, responseToReturn.status_code,
                    responseToReturn.headers.items())

        elif data["caller"] == "deleteRide":
            Ride.query.filter_by(ride_id=data["rideId"]).delete()
            db.session.commit()
            responseToReturn = Response()
            responseToReturn.status_code = 200
            return (responseToReturn.text, responseToReturn.status_code,
                    responseToReturn.headers.items())
Ejemplo n.º 7
0
def search_rides():
    """Searches database for rides"""

    # initialize to show 10 results ordered by date
    limit = 10
    cost = 50
    order_by = 'date'

    ### If user clicks 'All Rides' ###
    if request.args.get('query'):

        # Defaulting to the starting toggle points when viewing all rides
        state = ''
        start_time = datetime.strptime("12:00 AM", '%I:%M %p')
        start_time = datetime.combine(datetime.now().date(), start_time.time())
        start_time = to_utc(state, start_time).time()
        date_from = to_utc(state, datetime.now()).date()

        # Query database for all rides
        rides = Ride.get_rides(start_time=start_time,
                               date_from=date_from,
                               cost=cost,
                               limit=limit,
                               order_by=order_by)

        total_count = Ride.get_rides(start_time=start_time,
                                     date_from=date_from,
                                     cost=cost,
                                     order_by=order_by,
                                     count=True)
        # Round up page count with + 1
        page_count = int(math.ceil(float(total_count) / float(limit)))

        for ride in rides:
            # convert ride to local timezone
            ride.start_timestamp = to_local(ride.start_state,
                                            ride.start_timestamp)
            # turn date object into string for front end
            ride.start_timestamp = to_time_string(ride.start_state,
                                                  ride.start_timestamp)

        # Render search page, passing rides and page_count for pagination
        return render_template('search.html',
                               rides=rides,
                               page_count=page_count)

    ### If user enters search terms ###
    else:

        # Start with 15mile square search
        miles = 25
        deg = miles_to_degrees(miles)

        # Get search terms lat/lng
        start_lat = request.args.get('lat')
        start_lng = request.args.get('lng')
        end_lat = request.args.get('lat2')
        end_lng = request.args.get('lng2')

        if not start_lat or not start_lng:
            start_lat = 0.0
            start_lng = 0.0
        else:
            start_lat = float(start_lat)
            start_lng = float(start_lng)

        if not end_lat or not end_lng:
            end_lat = 0.0
            end_lng = 0.0
        else:
            end_lat = float(end_lat)
            end_lng = float(end_lng)

        # Dicts holding search terms to be placed in DOM and used by AJAX when
        #   user toggles search parameters
        start_search = {
            "term": request.args.get('searchstring', ''),
            "state": request.args.get('administrative_area_level_1', ''),
            "lat": start_lat,
            "lng": start_lng
        }
        end_search = {
            "term": request.args.get('searchstring2', ''),
            "state": request.args.get('administrative_area_level_1_2', ''),
            "lat": end_lat,
            "lng": end_lng
        }

        state = start_search['state']
        if not state_to_timezone(state):
            state = ''
        start_time = datetime.strptime("12:00 AM", '%I:%M %p')
        start_time = datetime.combine(datetime.now().date(), start_time.time())
        start_time = to_utc(state, start_time).time()
        date_from = to_utc(state, datetime.now()).date()
        # Get the first 10 results for query
        rides = Ride.get_rides(deg=deg,
                               start_lat=start_lat,
                               start_lng=start_lng,
                               end_lat=end_lat,
                               end_lng=end_lng,
                               limit=limit,
                               start_time=start_time,
                               date_from=date_from,
                               order_by=order_by)
        if len(rides) > limit:
            total_count = Ride.get_rides(deg=deg,
                                         start_lat=start_lat,
                                         start_lng=start_lng,
                                         end_lat=end_lat,
                                         end_lng=end_lng,
                                         limit=limit,
                                         start_time=start_time,
                                         date_from=date_from,
                                         order_by=order_by,
                                         count=True)
            # Round up page count with + 1
            page_count = int(math.ceil(float(total_count) / float(limit)))
        else:
            page_count = 1

        for ride in rides:
            # convert ride to local timezone
            ride.start_timestamp = to_local(ride.start_state,
                                            ride.start_timestamp)
            # turn date object into string for front end
            ride.start_timestamp = to_time_string(ride.start_state,
                                                  ride.start_timestamp)

        return render_template('search.html',
                               rides=rides,
                               start_search=start_search,
                               end_search=end_search,
                               page_count=page_count)
Ejemplo n.º 8
0
def process_rideform():
    """ Add new ride to database """

    ## V2. verify on backend. send AJAX request, if errors notify user

    # driver is logged in user
    driver = session['current_user']

    # retrieve form inputs
    seats = int(request.form.get('seats'))
    cost = int(float(request.form.get('cost')))

    start_string = request.form.get('start-address')
    start_lat = request.form.get('lat')
    start_lng = request.form.get('lng')
    start_number = request.form.get('street_number')
    start_street = request.form.get('route')
    start_city = request.form.get('locality')
    start_state = request.form.get('administrative_area_level_1')
    start_zip = request.form.get('postal_code')

    end_string = request.form.get('end-address')
    end_lat = request.form.get('lat2')
    end_lng = request.form.get('lng2')
    end_number = request.form.get('street_number2')
    end_street = request.form.get('route2')
    end_city = request.form.get('locality2')
    end_state = request.form.get('administrative_area_level_1_2')
    end_zip = request.form.get('postal_code2')

    date = request.form.get('date')
    time = request.form.get('time')

    start_time = datetime.strptime("{} {}".format(date, time),
                                   "%m/%d/%Y %I:%M %p")
    # Convert to utc
    start_time = to_utc(start_state, start_time)

    try:
        duration, mileage = get_directions(start_lat, start_lng, end_lat,
                                           end_lng, start_time)
    except:
        duration = None
        mileage = None

    luggage = request.form.get('luggage')
    comments = request.form.get('comments')
    pickup_window = request.form.get('pickup-window')
    detour = request.form.get('detour')
    car_type = request.form.get('cartype')

    # Create Ride Instance
    ride = Ride(
        driver=driver,
        seats=seats,
        cost=cost,
        start_lat=start_lat,
        start_lng=start_lng,
        start_number=start_number,
        start_street=start_street,
        start_city=start_city,
        start_state=start_state,
        start_zip=start_zip,
        end_lat=end_lat,
        end_lng=end_lng,
        end_number=end_number,
        end_street=end_street,
        end_city=end_city,
        end_state=end_state,
        end_zip=end_zip,
        start_timestamp=start_time,
        mileage=mileage,  #compute
        duration=duration,  #compute
        luggage=luggage,
        comments=comments,
        pickup_window=pickup_window,
        detour=detour,
        car_type=car_type)

    # validate fields
    ride = validate_ride(ride)

    #commit to db
    db.session.add(ride)
    db.session.commit()

    flash("Ride added to DB")

    return redirect('/profile/{}'.format(driver))
Ejemplo n.º 9
0
def json_test():
    """Return new ride results"""

    #Get search terms

    start_term = request.args.get('start_term')
    end_term = request.args.get('end_term')

    user_lat = request.args.get('user_lat')
    user_lng = request.args.get('user_lng')

    start_lat = request.args.get('start_lat')
    start_lng = request.args.get('start_lng')
    end_lat = request.args.get('end_lat')
    end_lng = request.args.get('end_lng')
    start_state = request.args.get("start_state")

    # Get search toggles (time, cost, date)

    start_time = request.args.get("start")
    cost = request.args.get("cost")

    date_from = request.args.get("date_from")
    date_to = request.args.get("date_to")

    limit = request.args.get("limit")
    offset = request.args.get("offset")
    offset = int(offset) * int(limit)
    order_by = request.args.get("order")

    # If there are no search terms, start_state will be an empty string. In this
    # case it it best to use the clients timezone to cater results to dates/ times in their
    # tz.
    if not start_state:
        # Using a try statement, because if google is unable to geocode the user,
        # I don't want this to error out, any would rather default to 'US/Pacific'
        try:
            start_state = (geocoder.google('{}, {}'.format(user_lat,
                                                           user_lng))).state
            # adding this check, because sometimes this returns odd strings
            if len(start_state) > 2:
                start_state = ''
        except:
            # Blank start states default to 'US/Pacific'
            start_state = ''
    if not state_to_timezone(start_state):
        start_state = ''

    # convert dates and time to utc to be queried against db
    if date_from:
        date_from = datetime.strptime(date_from, '%m/%d/%Y')
        date_from = to_utc(start_state, date_from).date()

    if date_to:
        date_to = datetime.strptime(date_to, '%m/%d/%Y')
        date_to = to_utc(start_state, date_to).date()

    start_time = datetime.strptime(start_time, '%I:%M %p')
    start_time = datetime.combine(datetime.now().date(), start_time.time())
    start_time = to_utc(start_state, start_time).time()
    print '\n\n*******\n{}\n****\n\n'.format(start_time)

    # Convert miles to lat/lng degrees
    deg = miles_to_degrees(25)

    rides = Ride.get_rides(deg=deg,
                           start_lat=start_lat,
                           start_lng=start_lng,
                           end_lat=end_lat,
                           end_lng=end_lng,
                           start_time=start_time,
                           cost=cost,
                           date_to=date_to,
                           date_from=date_from,
                           limit=limit,
                           offset=offset,
                           order_by=order_by)

    print '\nlimit: {}\noffset: {}\norder_by: {}\ndate_from: {}\nstart_time: {}\ncost: {}'.format(
        limit, offset, order_by, date_from, start_time, cost)

    total_count = Ride.get_rides(deg=deg,
                                 start_lat=start_lat,
                                 start_lng=start_lng,
                                 end_lat=end_lat,
                                 end_lng=end_lng,
                                 start_time=start_time,
                                 cost=cost,
                                 date_to=date_to,
                                 date_from=date_from,
                                 count=True)
    print '\ntotal_count: {}\n'.format(total_count)

    json_list = sqlalchemy_to_json(rides, total_count, limit)

    return jsonify(json_list)
Ejemplo n.º 10
0
def all_data():
    """Create some sample data."""

    # In case this is run more than once, empty out existing data
    print "deleting data"
    db.drop_all()

    db.create_all()

    # Add sample employees and departments
    with open('seed-data/users_seed.csv', 'rb') as ride_data:
        reader = csv.reader(ride_data,
                            quotechar="'",
                            delimiter=',',
                            quoting=csv.QUOTE_ALL,
                            skipinitialspace=True)
        reader.next()
        for row in reader:
            user = User(user_id=row[0],
                        fb_userid=row[1],
                        first_name=row[2],
                        last_name=row[3],
                        email=row[4],
                        image=row[5])
            db.session.add(user)
            db.session.commit()

    with open('seed-data/rides_seed.csv', 'rb') as ride_data:

        reader = csv.reader(ride_data,
                            quotechar="'",
                            delimiter=',',
                            quoting=csv.QUOTE_ALL,
                            skipinitialspace=True)
        reader.next()
        gmaps = googlemaps.Client(key=GOOGLE_KEY)

        geocode = defaultdict(defaultdict)

        for row in reader:
            route = row[15]

            if not geocode[route]:

                start_lat = row[3]
                start_lng = row[4]
                end_lat = row[5]
                end_lng = row[6]
                time.sleep(1)
                g_start = geocoder.google('{}, {}'.format(
                    start_lat, start_lng))
                time.sleep(1)
                g_end = geocoder.google('{}, {}'.format(end_lat, end_lng))

                geocode[route]['start_lat'] = start_lat
                geocode[route]['start_lng'] = start_lng
                geocode[route]['start_number'] = g_start.housenumber
                geocode[route]['start_street'] = g_start.street
                geocode[route]['start_city'] = g_start.city
                geocode[route]['start_state'] = g_start.state
                geocode[route]['start_zip'] = g_start.postal

                geocode[route]['end_lat'] = end_lat
                geocode[route]['end_lng'] = end_lng
                geocode[route]['end_number'] = g_end.housenumber
                geocode[route]['end_street'] = g_end.street
                geocode[route]['end_city'] = g_end.city
                geocode[route]['end_state'] = g_end.state
                geocode[route]['end_zip'] = g_end.postal

                start_time = datetime.strptime('4:00 PM', '%I:%M %p')
                today = datetime.now().date()
                start_datetime = datetime.combine(
                    datetime.now().date() + timedelta(days=1),
                    start_time.time())

                tz = state_to_timezone(geocode[route]['start_state'])
                start_time_aware = pytz.timezone(tz).localize(start_datetime)

                try:
                    directions_result = gmaps.directions(
                        "{},{}".format(start_lat, start_lng),
                        "{},{}".format(end_lat, end_lng),
                        traffic_model='best_guess',
                        departure_time=start_time_aware)

                    geocode[route]['duration'] = directions_result[0]['legs'][
                        0]['duration']['text']

                    geocode[route]['mileage'] = directions_result[0]['legs'][
                        0]['distance']['text']

                    print '\n\nduration: {}, mileage{}\n\n'.format(
                        geocode[route]['duration'], geocode[route]['mileage'])
                except Exception, e:
                    print '\n\nDuration/Mileage API Failed\n\n'
                    geocode[route]['mileage'] = None
                    geocode[route]['duration'] = None
                    print "Unexpected error:", start_lat, start_lng, end_lat, end_lng
                    print str(e)

            start_time = datetime.strptime(row[7], '%I:%M %p')
            today = datetime.now().date()
            day_offset = int(row[14])
            start_datetime = datetime.combine(
                datetime.now().date() + timedelta(days=day_offset),
                start_time.time())

            tz = state_to_timezone(geocode[route]['start_state'])
            # localize to US/Pacific
            start_time_aware = pytz.timezone(tz).localize(start_datetime)

            # Normalize to UTC
            start_time_utc = pytz.utc.normalize(start_time_aware)

            ride = Ride(
                driver=row[0],
                seats=row[1],
                cost=row[2],

                # Start Location
                start_lat=geocode[route]['start_lat'],
                start_lng=geocode[route]['start_lng'],
                start_number=geocode[route]['start_number'],
                start_street=geocode[route]['start_street'],
                start_city=geocode[route]['start_city'],
                start_state=geocode[route]['start_state'],
                start_zip=geocode[route]['start_zip'],
                # End Location
                end_lat=geocode[route]['end_lat'],
                end_lng=geocode[route]['end_lng'],
                end_number=geocode[route]['end_number'],
                end_street=geocode[route]['end_street'],
                end_city=geocode[route]['end_city'],
                end_state=geocode[route]['end_state'],
                end_zip=geocode[route]['end_zip'],

                # Date/Time
                start_timestamp=start_time_utc,

                #Details
                car_type=row[9],
                luggage=row[10],
                comments=row[11],
                pickup_window=row[12],
                detour=row[13],
                mileage=geocode[route]['mileage'],
                duration=geocode[route]['duration'])

            db.session.add(ride)
            db.session.commit()
        print geocode
Ejemplo n.º 11
0
db.session.add(driver)

driver = Driver(firstname='Neville',
                lastname='Longbottom',
                driver_location='Grimmauld Place',
                email='*****@*****.**',
                password='******')

# We need to add to the session or it won't ever be stored
db.session.add(driver)

#################################################################################
#Rides

ride = Ride(passenger_location='Forbidden Forest',
            passenger_destination='Ministry of Magic',
            pick_up_time='2016-06-12 13:00:00')

# We need to add to the session or it won't ever be stored
db.session.add(ride)

ride = Ride(passenger_location='Hogwarts',
            passenger_destination='Malfoy Mansion',
            pick_up_time='2016-06-20 16:00:00')

# We need to add to the session or it won't ever be stored
db.session.add(ride)

ride = Ride(passenger_location='Malfoy Mansion',
            passenger_destination='Hogwarts',
            pick_up_time='2016-06-20 16:15:00')