Exemplo n.º 1
0
def add_flight():
    matricula_aluno = request.json['matricula_aluno']
    registerDate = request.json['registerDate']
    dateTimeFlightStart = request.json['dateTimeFlightStart']
    dateTimeFlightEnd = request.json['dateTimeFlightEnd']
    comment = request.json['comment']
    grade = request.json['grade']

    new_flight = Flight(matricula_aluno, registerDate, dateTimeFlightStart,
                        dateTimeFlightEnd, comment, grade)
    new_flight.persist()

    return flight_schema.jsonify(new_flight)
Exemplo n.º 2
0
def trip_view(id):
    flight_form = AddFlightForm()
    trip = Trip.query.filter_by(id=id).first_or_404()
    num_flights = Flight.query.filter_by(trip_id=trip.id).count()
    num_stays = Stay.query.filter_by(trip_id=trip.id).count()
    num_events = Event.query.filter_by(trip_id=trip.id).count()
    if current_user not in trip.travelers:
        return render_template('errors/404.html')

    if flight_form.validate_on_submit():
        flight = Flight(
            code=flight_form.flight_number.data,
            trip_id=trip.id,
            start_datetime=to_utc_time(flight_form.departure_time.data),
            end_datetime=to_utc_time(flight_form.arrival_time.data))
        flight.users.append(current_user)
        db.session.add(flight)
        db.session.commit()
        flash('Your flight has been added!')
        return redirect(url_for('main.trip_view', id=id))
    return render_template(
        'itinerary.html',
        trip=trip,
        flight_form=flight_form,
        stay_form=AddStayForm(),
        event_form=AddEventForm(),
        travelers=trip.travelers,
        num_flights=num_flights,
        num_stays=num_stays,
        num_events=num_events,
    )
Exemplo n.º 3
0
def save():
    if not current_user.is_anonymous:
        flight_json = request.form["flight_info"]
        flight_json = json.loads(flight_json)
        flight = Flight(departure=flight_json['airportA'],
                        arrival=flight_json['airportB'],
                        departureTime=flight_json['dateDeparture'] + 'T' +
                        flight_json['timeDeparture'],
                        arrivalTime=flight_json['dateArrival'] + 'T' +
                        flight_json['timeArrival'],
                        airline=flight_json['airline'],
                        number=flight_json['number'])
        flight_check = Flight.query.filter_by(
            departureTime=flight.departureTime,
            arrivalTime=flight.arrivalTime,
            number=flight.number,
            airline=flight.airline).first()

        airlinesManager = AirlinesManager()
        airlinesManager.increase_count(flight_json['airline'],
                                       flight_json['dateArrival'])
        if flight_check is None:
            try:
                psqldb.session.add(flight)
            except:
                flash(_("Unable to add user to db"))
                return "fail"
            try:
                psqldb.session.commit()
                # to get generted id of just inserted
                flight_check = Flight.query.filter_by(
                    departureTime=flight.departureTime,
                    arrivalTime=flight.arrivalTime,
                    number=flight.number,
                    airline=flight.airline).first()
                # init saved_flights table for newly added flight
                saved_flight_manager = SavedFlightsManager()
                saved_flight_manager.init_flight(flight_check.id,
                                                 current_user.id)

            except Exception as e:
                flash(_("Some error accured"))
                print(e)
                return "fail"

        # add flight id to user saved flights
        user_activity_manager = UserActivityManager()
        user_activity_manager.insert_flight(flight_check.id, current_user.id,
                                            flight_json['fares'])

        saved_flight_manager = SavedFlightsManager()
        saved_flight_manager.add_saved_flight(flight_check.id, current_user.id,
                                              flight_json['fares'])

    else:
        return redirect(url_for('login'))

    return "success"
Exemplo n.º 4
0
def search():
    if not g.search_form.validate():
        return redirect(url_for('explore'))
    page = request.args.get('page', 1, type=int)
    flights, total = Flight.search(g.search_form.q.data, page, 6)

    next_url = url_for('search', q=g.search_form.q.data, page=page + 1) \
        if total > page * 6 else None
    prev_url = url_for('search', q=g.search_form.q.data, page=page - 1) \
        if page > 1 else None
    return render_template('search.html', title='Search', flights=flights,
                           next_url=next_url, prev_url=prev_url)
Exemplo n.º 5
0
def create_flight():
    data = request.get_json(force=True)
    flight = Flight(_from=data["_from"],
                    _to=data["_to"],
                    date_departure=data["date_departure"],
                    date_arrival=data["date_arrival"])
    db.session.add(flight)
    db.session.commit()
    flight = Flight.query.filter_by(id=flight.id).first()
    return jsonify(id=flight.id,
                   _from=flight._from,
                   _to=flight._to,
                   date_departure=flight.date_departure,
                   date_arrival=flight.date_arrival)
Exemplo n.º 6
0
def createFlight():
    form = FlightForm()
    staffname = session["username"]
    staff = Staff.query.filter_by(username=staffname).first()
    if form.validate_on_submit():
        data = form.data
        airplane = Airplane.query.filter_by(id=data["airplane_name"]).first()
        flight = Flight.query.filter_by(flight_num=data["flight_num"]).count()
        departure_airport = Airport.query.filter_by(
            name=data["departure_airport_name"]).first()
        arrival_airport = Airport.query.filter_by(
            name=data["arrival_airport_name"]).first()
        if flight == 1:
            flash("The flight number already exists!")
            return redirect(url_for("staff.createFlight"))
        if data["departure_airport_name"] == data["arrival_airport_name"]:
            flash(
                "Dont't input the same location about departure_airport_name and arrival_airport_name"
            )
            return redirect(url_for("staff.createFlight"))
        flight = Flight(flight_num=data["flight_num"],
                        departure_time=data["departure_time"],
                        arrival_time=data["arrival_time"],
                        departure_airport_name=data["departure_airport_name"],
                        arrival_airport_name=data["arrival_airport_name"],
                        departure_city=departure_airport.city,
                        arrival_city=arrival_airport.city,
                        price=data["price"],
                        status="upcoming",
                        rest_seat=airplane.seats,
                        airline_name=staff.airline_name,
                        airplane_id=data["airplane_name"])
        db.session.add(flight)
        db.session.commit()
        flash("Add success!")
        return redirect(url_for("staff.createFlight"))
    return render_template("staff/createFlight.html", form=form, staff=staff)
Exemplo n.º 7
0
            try:
                driver.find_element_by_class_name(
                    'r9-dialog-closeButton').click()
            except Exception:
                pass
            time.sleep(5)
            try:
                price_string = driver.find_elements_by_class_name(
                    'flightresult')[0].find_elements_by_class_name(
                        'pricerange')[0].text
                if price_string.replace('$', '').isdigit():
                    price = int(price_string.replace('$', ''))
                else:
                    raise ValueError()
                site = driver.find_elements_by_class_name(
                    'bookitprice')[0].get_attribute('href')
                flight = Flight(price=price,
                                site=site,
                                location_seed_id=location_seed.id)
                db.session.add(flight)
                db.session.commit()
            except Exception:
                print('Invalid information on the page')
    except Exception:
        print('Invalid information: {}, {}'.format(location_seed.city_name,
                                                   location_seed.country_name))

    index += 1
    print("Processing numbers: {}/{}.".format(index, location_seed_number))
driver.quit()
Exemplo n.º 8
0
def map_session_saved(sender, **kwargs):
    ms = kwargs['instance']
    channel = Channel(ms.channel)
    Facility.send_for_geometry(channel, ms.bounds)
    Flight.send_for_location_geometry(channel, ms.bounds)
    Weather.send_for_geometry(channel, ms.bounds)
Exemplo n.º 9
0
 def register_flight(self, model: RegisterFlightDto):
     flight = Flight()
     flight.aircraft_id = model.aircraft_id
     flight.takeoff_location = model.takeoff_location
     flight.destination = model.destination
     flight.departure_date = model.departure_date
     flight.arrival_time = model.arrival_time
     flight.flight_number = model.flight_number
     flight.price = model.price
     flight.date_created = model.date_created
     flight.save()
Exemplo n.º 10
0
    def _parse_response(self, response_dict):
        routes = []
        for i, route in enumerate(response_dict['routes']):
            # filter by transfers
            if self._search_request.no_transfers and len(
                    route['segments']) > 1:
                continue

            # create route obj
            rt = Route(
                order=i,
                pl_from=self._search_request.req_from,
                pl_to=self._search_request.req_to,
                from_seg=response_dict['places'][route['depPlace']]
                ['shortName'],
                transfers=len(route['segments']) - 1,
                duration=self._parse_duration(route['totalDuration']),
                duration_raw=route['totalDuration'],
            )

            # filter by total price
            if not route.get('indicativePrices'):
                continue
            else:
                pr = route['indicativePrices'][-1]
                if self._search_request.price_lower_limit and \
                        int(pr['price']) < self._search_request.price_lower_limit:
                    continue

                if self._search_request.price_upper_limit and \
                        int(pr['price']) > self._search_request.price_upper_limit:
                    continue

            # parse total price
            self._parse_price(route, rt)

            # parse segments
            segments = []
            types_set = set()
            for segment in route['segments']:
                transport_type = response_dict['vehicles'][
                    segment['vehicle']]['kind']
                types_set.add(transport_type)

            if any(not self._names.get(tr) for tr in types_set):
                continue

            for segment in route['segments']:
                # create segment dict
                transport_type = response_dict['vehicles'][
                    segment['vehicle']]['kind']
                seg = Segment(
                    to=self._limit_name(response_dict['places'][
                        segment['arrPlace']]['shortName']),
                    to_full=response_dict['places'][segment['arrPlace']]
                    ['shortName'],
                    transport_type=TransportType(
                        name=self._names[transport_type],
                        icon=self._icons[transport_type],
                    ),
                )

                # parse segment price
                if segment.get('indicativePrices'):
                    self._parse_price(segment, seg)
                else:
                    seg.price = '-'
                    seg.price_raw = 0

                # parsing specific segment type
                if segment['segmentKind'] == 'surface':
                    seg.segment_type = 'surface'
                    seg.duration = self._parse_duration(
                        segment['transitDuration'] +
                        segment['transferDuration'])
                    seg.duration_raw = segment['transitDuration'] + segment[
                        'transferDuration']
                    if segment.get('agencies'):
                        seg.frequency = self._parse_frequency(
                            segment['agencies'][0]['frequency'])
                        links = segment['agencies'][0]['links']
                        for link in links:
                            if link['text'] == 'Book at':
                                seg.book_name = link['displayUrl']
                                seg.book_url = link['url']
                            elif link['text'] == 'Schedules at':
                                seg.schedule_name = link['displayUrl']
                                seg.schedule_url = link['url']
                # end
                else:
                    seg.segment_type = 'air'
                    if segment.get('outbound'):
                        duration = 0
                        leg = segment['outbound'][0]

                        start_index = leg['hops'][0]['depPlace']
                        time_start = leg['hops'][0]['depTime']
                        for hop in leg['hops']:
                            end_index = hop['arrPlace']
                            duration += hop['duration']
                            time_end = hop['arrTime']

                        seg.airport_start_code = response_dict['places'][
                            start_index]['code']
                        seg.airport_start_name = response_dict['places'][
                            start_index]['shortName']
                        seg.airport_end_code = response_dict['places'][
                            end_index]['code']
                        seg.airport_end_name = response_dict['places'][
                            end_index]['shortName']
                        seg.time_start = time_start
                        seg.time_end = time_end
                        seg.duration = self._parse_duration(duration)
                        seg.duration_raw = duration
                        seg.operating_days = self._parse_days(
                            leg['operatingDays'])

                        flights = []
                        for leg in segment['outbound']:
                            flight = Flight(operating_days=self._parse_days(
                                leg['operatingDays']))
                            if leg.get('indicativePrices'):
                                self._parse_price(leg, flight)

                            duration = 0
                            hops = []
                            airlines = []
                            for hop in leg['hops']:
                                duration += hop['duration']
                                start_index = hop['depPlace']
                                end_index = hop['arrPlace']
                                hp = FlightSegment(
                                    airport_start_code=response_dict['places']
                                    [start_index]['code'],
                                    airport_start_name=response_dict['places']
                                    [start_index]['shortName'],
                                    airport_end_code=response_dict['places']
                                    [end_index]['code'],
                                    airport_end_name=response_dict['places']
                                    [end_index]['shortName'],
                                    time_start=hop['depTime'],
                                    time_end=hop['arrTime'],
                                    duration=self._parse_duration(
                                        hop['duration']),
                                    duration_raw=hop['duration'],
                                    airline_name=response_dict['airlines'][
                                        hop['airline']]['name'],
                                )
                                hops.append(hp)
                                airlines.append(response_dict['airlines'][
                                    hop['airline']]['name'])

                            flight.flight_segments = hops
                            flight.duration_raw = duration
                            flight.duration = self._parse_duration(duration)
                            flight.airlines = ', '.join(a
                                                        for a in set(airlines))
                            flights.append(flight)

                        flights_obj = Flights(choices=flights).save()
                        seg.flights = flights_obj
                # end
                segments.append(seg)
            # end

            # parse transport types
            transport_types = [
                TransportType(
                    name=self._names[tp],
                    icon=self._icons[tp],
                ) for tp in types_set
            ]

            rt.segments = segments
            rt.transport_types = transport_types
            routes.append(rt)

        self._save_best_route(routes)
        self._search_request.routes = routes
        self._search_request.save()
        return self._search_request.result