def insert_trips(file_name): line_num = 0 pick_up = True with open(file_name, 'r') as csv_file: reader = csv.reader(csv_file, delimiter=',') for row in reader: line_num += 1 # Skip header if line_num == 1: print("Header row, skipping") continue if pick_up: pick_up = False date_object = datetime.strptime(row[0], '%m/%d/%Y %H:%M:%S') pickup_lat = float(row[1]) pickup_lng = float(row[2]) pickup_location = str(pickup_lat) + ',' + str(pickup_lng) else: pick_up = True drop_off_lat = float(row[1]) drop_off_lng = float(row[2]) drop_off_location = str(drop_off_lat) + ',' + str(drop_off_lng) # This statement will insert a single row into the table called trips db.session.add(Trip(date_object, pickup_lat, pickup_lng, drop_off_lat, drop_off_lng, pickup_location, drop_off_location)) db.session.commit() print("Done iterating over file contents - the file has been closed now!")
def insert_json_into_db(cls, username, json): user = cls.session.query(User).filter_by(username=username).first() user.trips.extend([ Trip(trip=trip, srid=settings.TARGET_DATUM) for trip in json if len(trip['path']) > 1 ]) cls.session.commit()
def on_post(self, req, resp): print('POST!!!!!!!!!!!!!!!!!!') data = req.json if not self._is_valid_request_payload(data): raise falcon.HTTPBadRequest() try: origin = self._get_location(Origin, data['origin']) req.db.save(origin) except KeyError: raise falcon.HTTPBadRequest('Invalid origin payload') try: destination = self._get_location(Destination, data['destination']) req.db.save(destination) except KeyError: raise falcon.HTTPBadRequest('Invalid destination payload') trip = Trip(drive_or_ride=data['driveOrRide'], origin=origin, destination=destination, user=req.current_user, time=parser.parse(data['time']) ) # data['time'] example: 2016-10-19T20:17:52.2891902Z req.db.save(trip) resp.json = self._get_serialize_trip(trip) resp.status = falcon.HTTP_CREATED
def add(): form = TripForm() if form.validate_on_submit(): url = form.url.data description = form.description.data destination = form.destination.data outbound_date = form.outbound_date.data outbound_time = form.outbound_time.data inbound_date = form.inbound_date.data inbound_time = form.inbound_time.data tags = form.tags.data bm = Trip(user=current_user, url=url, description=description, destination=destination, tags=tags, outbound_date=outbound_date, outbound_time=outbound_time, inbound_date=inbound_date, inbound_time=inbound_time) db.session.add(bm) db.session.commit() flash("Stored trip '{}'".format(description)) return redirect(url_for('index')) return render_template('trip_form.html', form=form, title="Add a Trip")
def make_a_trip(self): from models import Trip, User, Origin, Destination session = self.get_session() user = User(username='******', email='*****@*****.**', phone='123456789', auth0_id='123') session.save(user) origin = Origin(street='Baker St', street_number='221B', colony_or_district='Marylebone', city='London', state='Marylebone', country='UK', zipcode='NW1 6XE') session.save(origin) destination = Destination(street='Wallaby Way', street_number='42', colony_or_district='-', city='Sydney', state='New South Wales', country='Australia', zipcode='31351') session.save(destination) trip = Trip(drive_or_ride='Drive', time=parser.parse('2110-10-20 03:17:52 UTC'), origin=origin, destination=destination, user=user) session.save(trip)
def handle_post(self, email, account_info): if self.request.get("trip_entity_key"): trip = self.request.get("trip_entity_key").get() trip.capacity_left = int(self.request.get("capacity")) else: trip = Trip(parent=trip_utils.get_parent_key_from_username( account_info.rose_username)) if self.request.get("role_radio_group") == "driver": trip.driver = account_info.key elif self.request.get("role_radio_group") == "passenger": trip.passengers.append(account_info.key) else: raise Exception("wrong value") trip.origin = self.request.get("origin") trip.destination = self.request.get("destination") pick_up_time = date_utils.get_utc_datetime_from_user_input( account_info.time_zone, self.request.get("pick_up_time")) trip.pick_up_time = pick_up_time trip.price = self.request.get("price") if self.request.get("capacity"): trip.capacity_left = int(self.request.get("capacity")) else: trip.capacity_left = 0 trip.put() trip_utils.send_email(email, account_info, trip.origin, trip.destination, trip.pick_up_time, False, False, True) self.redirect("/find-trip")
def post_trip(user): body = request.get_json() new_trip = Trip(id_traveler=user['id'], needs_trip=body['needs_trip'], destination=body['destination'], first_day=body['first_day'], last_day=body['last_day'], description=body['description']) db.session.add(new_trip) db.session.commit() new_travel_json = new_trip.serialize() return jsonify(new_travel_json), 200
def make_test_trip(): from models import Trip import datetime trip = Trip() trip.start_location = "Here" trip.end_location = "There" trip.start_datetime = datetime.datetime.now() trip.end_datetime = datetime.datetime.now() trip.save()
def createNewTrip(user_id): if request.method == 'POST': phone_no = request.json.get('phone_no') traveling_from_state = request.json.get('traveling_from_state') traveling_from_city = request.json.get('traveling_from_city') traveling_to_state = request.json.get('traveling_to_state') traveling_to_city = request.json.get('traveling_to_city') traveling_date = request.json.get('traveling_date') posted_on = request.json.get('posted_on') time_updated = request.json.get('time_updated') user = session.query(User).filter_by(id=user_id).first() profile_image = user.picture user_first_name = user.first_name user_last_name = user.last_name user_id = user_id newTrip = Trip(phone_no=phone_no, traveling_from_state=traveling_from_state, traveling_from_city=traveling_from_city, traveling_to_state=traveling_to_state, traveling_to_city=traveling_to_city, traveling_date=traveling_date, posted_on=posted_on, time_updated=time_updated, profile_image=profile_image, user_id=user_id, user_first_name=user_first_name, user_last_name=user_last_name) session.add(newTrip) session.commit() trip_payload = {} trip_payload['profile_image'] = user.picture trip_payload['id'] = newTrip.id trip_payload['phone_no'] = phone_no trip_payload['traveling_from_state'] = traveling_from_state trip_payload['traveling_from_city'] = traveling_to_city trip_payload['traveling_to_state'] = traveling_to_state trip_payload['traveling_to_city'] = traveling_to_city trip_payload['traveling_date'] = traveling_date trip_payload['posted_on'] = posted_on trip_payload['time_updated'] = time_updated trip_payload['user_id'] = user_id trip_payload['user_first_name'] = user_first_name trip_payload['user_last_name'] = user.last_name raw = {"data": trip_payload} trip_data = json.dumps(raw) #result = push_service.notify_single_device(registration_id = reg_id, data_message= payload) result = push_service.notify_topic_subscribers( topic_name=TRIP_TOPIC, data_message=trip_payload) pprint(result) return trip_data
def add_trip_form(): if not current_user.is_authenticated: return redirect('/trips') if request.method == 'POST': name = request.form.get('name') photo_url = request.form.get('photo_url') published = request.form.get('published') try: trip = Trip(name=name, photo_url=photo_url, published=published) db.session.add(trip) db.session.commit() return "Trip added. trip id={}".format(trip.id) except Exception as e: return (str(e)) return render_template("trips/new.html")
def create_trip(jwt): body = request.get_json() name = body.get('name', None) start_date = body.get('start_date', None) end_date = body.get('end_date', None) if (name is None or name == ''): abort(400) try: new_trip = Trip(name=name, start_date=start_date, end_date=end_date) new_trip.insert() return jsonify({'success': True, 'trip_id': new_trip.id}) except: abort(422)
def insert_trip(trip_id, route_id, service_id, shape_id): """ insert a new trip :param trip_id: str, id of trip :param route_id: str, id of route :param service_id: str, id of service, :param shape_id: str, id of shape :return: """ route = Route.objects.get(route_id=route_id) service = Calender.objects.get(service_id=service_id) shape = Shape.objects.get(shape_id=shape_id) d = Trip(trip_id=trip_id, route_id=route, service_id=service, shape_id=shape) d.save()
def post(self): if not WhiteTokenModel.is_jti_whitelisted(get_raw_jwt()["jti"]): return {'message': 'Not logged in'}, 205 data = post_trip_parser.parse_args() print("Test print", flush=True) try: existing_trip = Trip.does_trip_exist(data["trip"]) if (existing_trip["exists"]): return {"message": "The trip already exist"}, 200 current_user = get_jwt_identity() if (not data["public"]): public = True else: public = bool(data["public"]) if not data["trip"]: return {'message': 'You need to provide a trip'} else: #TODO: Improve this \/ tid = random.randint(10000000, 99999999) while Trip.find_by_tid(tid): if tid >= 99999999: tid = 10000000 else: tid += 1 new_trip = Trip(trip_id=tid, user_id=current_user, trip_json=data["trip"], is_public=public) new_trip.save_to_db() return { "message": "The trips was uploaded successfully", "tripid": tid }, 201 except Exception as err: return {"message": str(err)}, 500
def store_trip(from_bldg, to_bldg, method, time, timestamp): # convert time to int time = int(time) # validate all input if (not validate_building(from_bldg) or not validate_building(to_bldg) or not validate_method(method)): return ("Your input is invalid! Please try again.", 400) if (time < 1): return ( "Your time seems really short... Have you started the timer?", 400) trip = Trip(from_building=from_bldg, to_building=to_bldg, method=method, time=time, timestamp=timestamp) DBSession.add(trip) DBSession.commit() DBSession.close() return ("Thank you! Your trip has been recorded.", 201)
def edit(id=0): setExits() id = cleanRecordID(id) if id < 0: flash("That is not a valid ID") return redirect(g.listURL) rec = None if id > 0: rec = Trip.query.get(id) if not rec: flash( printException( "Could not edit that " + g.title + " record. ID=" + str(id) + ")", 'error')) return redirect(g.listURL) form = TripForm(request.form, rec) ## choices need to be assigned before rendering the form # AND before attempting to validate it form.countEvent_ID.choices = getCountEventChoices() form.location_ID.choices = getLocationChoices() form.traveler_ID.choices = getTravelerChoices() form.turnDirection.choices = getTurnDirectionChoices() if request.method == 'POST' and form.validate(): if not rec: rec = Trip(form.tripCount.data, form.tripDate.data, form.turnDirection.data, form.seqNo.data, form.location_ID.data, form.traveler_ID.data, form.countEvent_ID.data) db.session.add(rec) form.populate_obj(rec) db.session.commit() return redirect(g.listURL) return render_template('genericEditForm.html', rec=rec, form=form)
def handle_post(self, email): if self.request.get("trip_entity_key"): trip_key = ndb.Key(urlsafe=self.request.get("trip_entity_key")) trip = trip_key.get() else: trip = Trip(parent=utils.get_parent_key_for_email(email)) trip.state = self.request.get("state") trip.city = self.request.get("city") trip.start_date = self.request.get("arrival-date") trip.end_date = self.request.get("departure-date") trip.description = self.request.get("description") # last touch modified time update? or nah? # image if self.get_uploads() and len(self.get_uploads()) == 1: logging.info("Received an image blob with this trip.") media_blob = self.get_uploads()[0] trip.media_blob_key = media_blob.key() else: logging.info("This is a trip without an image attachment.") trip.put() self.redirect(self.request.referer)
def editTripsFromList(id): setExits() tripData = {} #empty dictionary id = cleanRecordID(id) if id > 0: rec = Assignment.query.get(id) if not rec: return "failure: Assignment record not found" tripCount = getAssignmentTripTotal(id) if tripCount > 0: return "failure: There are already trips recorded." # Get travelers travelers = getTravelersForEvent(rec.countEvent_ID) #populate tripData with info on manually enterd counts tripData = getTurnData(rec) countEvent = CountEvent.query.get(rec.countEvent_ID) timeFrames = getTripTimeFrames( getDatetimeFromString(countEvent.startDate), getDatetimeFromString(countEvent.endDate)) if request.method == "POST": # Validate form? result = True # record trips for countInputName in tripData.keys(): if not request.form[countInputName]: tripCount = 0 else: tripCount = request.form[countInputName] turnLeg = tripData[countInputName][1] travelerID = tripData[countInputName][2] try: tripCount = int(tripCount) #this may throw a ValueError if tripCount < 0: result = False raise ValueError("Negative values are not allowed.") if tripCount != tripData[countInputName][0]: #delete the previous manual trips, if any # gin up the possible start and end times startTime, endTime = getTimeStampFromTimeFrame( tripData[countInputName][3].split("-")[0], countEvent.startDate) try: trips = Trip.query.filter( Trip.countEvent_ID == rec.countEvent_ID, Trip.location_ID == rec.location_ID, Trip.traveler_ID == travelerID, Trip.tripDate >= startTime, Trip.tripDate <= endTime, Trip.turnDirection == turnLeg, Trip.seqNo == "000").delete() except: pass #the trip records may not exist if tripCount > 0: # genterate the trip time stamp startTime, endTime = getTimeStampFromTimeFrame( tripData[countInputName][3].split("-")[0], countEvent.startDate) try: cur = Trip(tripCount, endTime, turnLeg, "000", rec.location_ID, travelerID, rec.countEvent_ID) db.session.add(cur) except Exception as e: result = False flash( printException( 'Could not record Trip for ' + turnLeg, "error", e)) except ValueError as e: result = False #remove the 'standard' errpr message mes = "%s" % (e) if mes[0:7] == 'invalid': mes = '' trav = Traveler.query.get(travelerID) errTrav = "a traveler" if trav: errTrav = trav.name flash("The value '%s' in turn %s of %s is invalid. %s" % (tripCount, turnLeg, errTrav, mes)) if result: db.session.commit() return "success" # this is an ajax request else: db.session.rollback() tripData = getTurnData(rec, request.form) flash("No changes were saved.") # render form return render_template('assignment/editTrips.html', rec=rec, travelers=travelers, tripData=tripData, timeFrames=timeFrames) return "failure: Unable to edit trips for Assignment"
def post(self): errors = [] output = "" user = users.get_current_user() authz = Authz(user) self.response.headers["Content-type"] = "application/json" # check for authorization to create new trips & verify this is in fact # a request to create a new trip try: # user allowed to create trips? authz.createTrip() except PermissionError as e: # this permission error could have come from authz or locally errors.append({"message": e.args}) # bail if we hit authz errors if len(errors) > 0: self.response.set_status(400) output = json.dumps({"error": errors}) self.response.out.write(output) return # user is allowed, so go ahead and try to create this thing #logging.debug(self.request.body) data = TripUnpacker().unpack_post(self.request) #logging.debug(data) if data['name'] == "" or data['password'] == "": errors.append({"message": "Trip name and password are required."}) else: try: trip = Trip(name=data['name'], password=data['password'], owner=user) # get traveler names raw_travelers = data['travelers'] if len(raw_travelers) > Config.limits.travelers_per_trip: logging.warning('Attempt to add too many travelers: %s', user.nickname) raw_travelers = raw_travelers[:Config.limits. travelers_per_trip] travelers = [] for traveler in raw_travelers: if traveler.strip() != "": travelers.append(traveler.strip()) trip.travelers = travelers # get dates # TODO: validation that these dates are sane and properly ordered start_date = dateparse(data['start_date']) end_date = dateparse(data['end_date']) trip.start_date = start_date.date() #logging.debug("start date = " + str(start_date.date())) trip.end_date = end_date.date() #logging.debug("end date = " + str(end_date.date())) trip.put() output = GqlEncoder().encode({ "id": "%s" % trip.key(), 'modify_date': trip.modify_date, 'start_date': trip.start_date, 'end_date': trip.end_date, }) except Exception as e: logging.exception(e) errors.append({"message": "Unexpected error creating trip"}) if len(errors) > 0: self.response.set_status(400) output = json.dumps({"error": errors}) self.response.out.write(output)
def create_trip(self): t = Trip('01:00', '02:00', '10.1') return t
def driver_multiple_trips(self, create_driver_with_trips): d = create_driver_with_trips t = Trip('02:00', '15:00', '50') d.add_trip(t) return d
def create_driver_with_trips(self, create_driver): d = create_driver t = Trip('01:00', '02:00', '17.3') d.add_trip(t) return d
if __name__ == '__main__' or __name__ == '__init__': print(gethostname()) # Remove all entries. base.metadata.drop_all(bind=engine) # Create tables. base.metadata.create_all(bind=engine) """ Example database operations. """ # ADDING: db_session = create_db_session() user1 = User('admin', 'admin', 'Ad Min', '*****@*****.**', 'CAD') user2 = User('user2', 'user2', 'Us Er2', '*****@*****.**', 'USD') db_session.add_all([user1, user2]) trip1 = Trip(1, 'admin_trip', True, to_datetime('Sat, 10 Aug 2013 07:00:00 GMT'), to_datetime('Sat, 17 Aug 2013 08:00:00 GMT'), 'admin') trip2 = Trip(2, 'user2_trip', True, to_datetime('Sat, 10 Aug 2013 08:00:00 GMT'), to_datetime('Sat, 24 Aug 2013 09:00:00 GMT'), 'user2') trip3 = Trip(3, 'admin_trip3', True, to_datetime('Sat, 17 Aug 2013 04:00:00 GMT'), to_datetime('Sat, 24 Aug 2013 05:00:00 GMT'), 'admin') db_session.add_all([trip1, trip2, trip3]) event1 = Event(1, 'test', to_datetime('Mon, 11 Aug 2013 15:15:15 GMT'), to_datetime('Mon, 11 Aug 2013 16:16:16 GMT'), None, None, True, None, None, 1) event2 = Event(2, 'testVancouver', to_datetime('Tue, 12 Aug 2013 17:17:17 GMT'), to_datetime('Tue, 12 Aug 2013 18:18:18 GMT'), 49.267132, -122.968941, True, None, "6511 Sumas Dr Burnaby,BC V5B 2V1",
def trips(tripID=None): curr_userName = session.get(KEY__USERNAME) if curr_userName is None: return make_response('A User session is required to view Trips.', 401) if request.method == POST: try: post_tripName = str(request.json['tripName']) post_active = str(request.json['active']) post_startDate = to_datetime(str(request.json['startDate'])) post_endDate = to_datetime(str(request.json['endDate'])) except (KeyError, ValueError) as err: return bad_request(err) db = create_db_session() try: max_id = db.query(func.max( Trip.tripID).label('max_id')).first().max_id if max_id is None: max_id = 0 # No entries created yet. trip = Trip(max_id + 1, post_tripName, post_active, post_startDate, post_endDate, curr_userName) except ValueError as ve: close_session(db) return bad_request(ve) try: db.add(trip) db.commit() return make_response(jsonify({'trip': trip.to_dict()}), 201) except IntegrityError: db.rollback() # This should not occur given that we auto increment max EventID. # This might occur if multiple users are adding at the same time. return make_response('Conflict - TripID taken.', 409) finally: close_session(db) elif request.method == GET: post_tripID = request.args.get('tripID', None) db = create_db_session() try: if post_tripID: trip = db.query(Trip).filter( Trip.tripID == post_tripID).first() if trip is None: return make_response('Trip not found.', 404) if trip.userName != curr_userName: return make_response( 'User not authorized to view this Trip.', 401) return make_response(jsonify({'trip': [trip.to_dict()]}), 200) else: trip_list = db.query(Trip).filter( Trip.userName == curr_userName).all() if len(trip_list) == 0: return make_response('No Trips found.', 404) trips_dict = {'trips': [trip.to_dict() for trip in trip_list]} return make_response(jsonify(trips_dict), 200) finally: close_session(db) elif tripID: db = create_db_session() trip = db.query(Trip).filter(Trip.tripID == tripID).first() if trip is None: close_session(db) return make_response('Trip not found.', 404) userName = trip.userName if request.method == PUT: if userName != curr_userName: close_session(db) return make_response('User not authorized to edit Trip.', 401) try: # Optional tripName parameter. post_tripName = str(request.json['tripName']) trip.tripName = post_tripName except KeyError: pass try: # Optional active parameter. post_active = request.json['active'] trip.active = post_active except KeyError: pass try: # Optional name startDate. post_startDate = str(request.json['startDate']) trip.startDate = to_datetime(post_startDate) except ValueError as ve: close_session(db) return bad_request(ve) except KeyError: pass try: # Optional endDate parameter. post_endDate = str(request.json['endDate']) trip.endDate = to_datetime(post_endDate) except ValueError as ve: close_session(db) return bad_request(ve) except KeyError: pass ret_dict = {'trip': trip.to_dict()} close_session(db) return make_response(jsonify(ret_dict), 200) elif request.method == DELETE: if userName != curr_userName: close_session(db) return make_response('User not authorized to delete Trip.', 401) db.delete(trip) close_session(db) return make_response('Event deleted successfully', 200) return bad_request()
def post(self): request_dict = request.get_json() if not request_dict: resp = {'message': 'No input data provided'} return resp, status.HTTP_400_BAD_REQUEST errors = trip_schema.validate(request_dict) if errors: return errors, status.HTTP_400_BAD_REQUEST else: # create a new trip object and validate data trip_owner = Owner.query.filter_by( name=request_dict['owner']['name']).first() if trip_owner is None: # owner does not exist resp = {'message': 'owner does not exist'} return resp, status.HTTP_400_BAD_REQUEST # new_trip.owner_id = trip_owner.id trip_bookable_room = BookableRoom.query. \ filter(BookableRoom.resort.has(name=request_dict['bookable_room']['resort']['name'])). \ filter(BookableRoom.room_type.has( name=request_dict['bookable_room']['room_type']['name'])).first() if trip_bookable_room is None: # Resort does not exist resp = {'message': 'bookable room does not exist'} return resp, status.HTTP_400_BAD_REQUEST new_trip = Trip(trip_owner, trip_bookable_room) new_trip.check_in_date = datetime.strptime( request_dict['check_in_date'].split('T')[0], '%Y-%m-%d') new_trip.check_out_date = datetime.strptime( request_dict['check_out_date'].split('T')[0], '%Y-%m-%d') if new_trip.check_in_date >= new_trip.check_out_date: resp = {'message': 'check out must be after check in date'} return resp, status.HTTP_400_BAD_REQUEST new_trip.booked_date = datetime.strptime( request_dict['booked_date'].split('T')[0], '%Y-%m-%d') new_trip.notes = request_dict['notes'] new_trip.points_needed = request_dict['points_needed'] if new_trip.points_needed < 0: resp = {'message': 'points needed must be at least 1'} return resp, status.HTTP_400_BAD_REQUEST db.session.flush() # New trip is valid now try to allocate points current_use_year = new_trip.check_in_date previous_use_year = current_use_year+relativedelta(years=-1) next_use_year = current_use_year+relativedelta(years=1) previous_two_use_year = current_use_year+relativedelta(years=-2) booked_date = new_trip.booked_date personal_points_needed = new_trip.points_needed trip_owner_id = new_trip.owner_id # Find banked personal points personal_points_banked = db.session.query(PersonalPoint)\ .filter(PersonalPoint.owner_id == trip_owner_id, PersonalPoint.trip_id.is_(None), PersonalPoint.use_year < previous_use_year)\ .order_by("use_year").order_by("point_number")\ .limit(personal_points_needed).all() for point in personal_points_banked: point.trip_id = new_trip.id personal_points_needed -= len(personal_points_banked) # IF more points needed look for current personal points if personal_points_needed > 0: personal_points_current = db.session.query(PersonalPoint)\ .filter(PersonalPoint.use_year < current_use_year, PersonalPoint.use_year > previous_use_year)\ .filter(PersonalPoint.owner_id == new_trip.owner_id)\ .filter(PersonalPoint.trip_id.is_(None))\ .order_by("use_year").order_by("point_number")\ .limit(personal_points_needed).all() for point in personal_points_current: point.trip_id = new_trip.id personal_points_needed -= len(personal_points_current) else: personal_points_current = [] # IF more points needed look for borrow personal points if personal_points_needed > 0: personal_points_borrow = db.session.query(PersonalPoint) \ .filter(PersonalPoint.use_year < next_use_year, PersonalPoint.use_year > current_use_year) \ .filter(PersonalPoint.owner_id == new_trip.owner_id) \ .filter(PersonalPoint.trip_id.is_(None)) \ .order_by("use_year").order_by("point_number") \ .limit(personal_points_needed).all() for point in personal_points_borrow: point.trip_id = new_trip.id personal_points_needed -= len(personal_points_borrow) else: personal_points_borrow = [] # IF more personal points requirement was satisfied if personal_points_needed > 0: db.session.rollback() resp = { 'message': 'personal points shortage of %s points' % personal_points_needed} return resp, status.HTTP_400_BAD_REQUEST # FIND actual points actual_points_needed = new_trip.points_needed actual_points_banked = db.session.query(ActualPoint)\ .filter(ActualPoint.use_year < previous_use_year, ActualPoint.use_year > previous_two_use_year)\ .filter(ActualPoint.trip_id.is_(None))\ .filter(ActualPoint.banked_date < booked_date) \ .order_by("use_year").order_by("point_number") \ .limit(actual_points_needed).all() for point in actual_points_banked: point.trip_id = new_trip.id actual_points_needed -= len(actual_points_banked) # IF actual points requirement is satisfied if actual_points_needed > 0: actual_points_current = db.session.query(ActualPoint)\ .filter(ActualPoint.use_year < current_use_year, ActualPoint.use_year > previous_use_year)\ .filter(ActualPoint.trip_id.is_(None))\ .filter(or_(ActualPoint.banked_date.is_(None), ActualPoint.banked_date > booked_date)) \ .order_by("use_year").order_by("point_number") \ .limit(actual_points_needed).all() for point in actual_points_current: point.trip_id = new_trip.id actual_points_needed -= len(actual_points_current) else: actual_points_current = [] # IF actual points requirement is satisfied if actual_points_needed > 0: actual_points_borrow = db.session.query(ActualPoint)\ .filter(ActualPoint.use_year < next_use_year, ActualPoint.use_year > current_use_year)\ .filter(ActualPoint.trip_id.is_(None))\ .order_by("use_year").order_by("point_number")\ .limit(actual_points_needed).all() for point in actual_points_borrow: point.trip_id = new_trip.id actual_points_needed -= len(actual_points_borrow) else: actual_points_borrow = [] # IF more personal points requirement was satisfied if actual_points_needed > 0: db.session.rollback() resp = { 'message': 'actual points shortage of %s points' % actual_points_needed} return resp, status.HTTP_400_BAD_REQUEST # ALL is good commit to db and return success try: log_event(get_jwt_identity(), 'CREATE - ' + new_trip.__repr__()) log_event(get_jwt_identity(), 'Personal Points Allocated: [%s,%s,%s]' % (len(personal_points_banked), len(personal_points_current), len(personal_points_borrow))) log_event(get_jwt_identity(), 'Actual Points Allocated: [%s,%s,%s]' % (len(actual_points_banked), len(actual_points_current), len(actual_points_borrow))) db.session.commit() result = trip_schema.dump(new_trip) return result, status.HTTP_201_CREATED except SQLAlchemyError as e: db.session.rollback() resp = jsonify({"error": str(e)}) resp.status_code = status.HTTP_400_BAD_REQUEST return resp
def object_loader(self, input_data): """ parses through the input data and loads it into the object data member of this report engine class. Creates a dictionary where the key is a driver object and the value is a list of trips associated with the driver. """ # two lists created for categorizing the input types driver_list = list() trip_list = list() # iterate through the inputs for input in input_data: input_words = input.split() # checks if the input command is driver or trip # puts the command in the respective bucket if input_words[0].lower().capitalize() == DRIVER: driver_list.append(input) elif input_words[0].lower().capitalize() == TRIP: trip_list.append(input) # iterate through the driver command list # and make it a key for the object data for driver_text in driver_list: driver_data = driver_text.split() driver_name = driver_data[1] # create list of driver names for checking if name is in list drive_obj_names = [ driver.name for driver, trip_list in self.object_data.items() ] # if the driver name is not in the list, create a new key as the Driver object if driver_name not in drive_obj_names: new_driver = Driver(driver_name) self.object_data[new_driver] = list() # iterate through the trip commands for trip_text in trip_list: trip_data = trip_text.split() text_trip_driver = trip_data[1] text_start_time = trip_data[2] text_end_time = trip_data[3] text_distance = trip_data[4] # create a new Trip object new_trip = Trip(text_start_time, text_end_time, text_distance) # iterate through object_data for checking on the name for key, value in self.object_data.items(): # if the driver name and trip driver is the same # append to the list of the trips for the object_data if key.name == text_trip_driver: self.object_data[key].append(new_trip) # final iteration where the trips are added as children to the # actual driver objects instead of just in the object_data structure for driver_obj, trip_list in self.object_data.items(): for trip in trip_list: driver_obj.add_trip(trip)