Exemplo n.º 1
0
def index(
):  # By convention, the home page of websites is often index.html hence the route here is named index
    # Create sample flight and passenger objects to provide some data to work with as we don't have a database
    f1 = Flight(flight_num="AZ1244", origin="New York", destination="Paris")
    p1 = Passenger(firstname="Paris", lastname="Holt")
    p2 = Passenger(firstname="Susan", lastname="York")
    f1.add_passenger(p1)
    f1.add_passenger(p2)
    f2 = Flight(flight_num="BB9876", origin="Paris", destination="Tokyo")
    f2.add_passenger(p2)
    # render the view using the index.html template, passing the flight details to the template
    return render_template('index.html', flights=[f1, f2])
Exemplo n.º 2
0
    def create_flight(jwt):
        body = request.get_json()
        origin = body.get('origin', None)
        destination = body.get('destination', None)
        time = body.get('time', None)
        booked = body.get('booked', None)
        trip = body.get('trip', None)

        if (origin is None or destination is None or trip is None
                or origin == '' or destination == '' or trip == ''):
            abort(400)

        db_trip = Trip.query.get(trip)
        if (db_trip is None):
            abort(400)

        try:
            new_flight = Flight(origin=origin,
                                destination=destination,
                                time=time,
                                booked=booked,
                                trip=trip)
            new_flight.insert()

            return jsonify({'success': True, 'flight_id': new_flight.id})

        except:
            abort(422)
Exemplo n.º 3
0
def incoming_flight_data():
    JSON = request.json
    flight_num = JSON.get('flight_num')
    latitude = JSON.get('latitude')
    longitude = JSON.get('longitude')
    altitude = JSON.get('altitude')
    speed = JSON.get('speed')
    temperature = JSON.get('temperature')
    flight_key_urlsafe = JSON.get('flight_key_urlsafe') if 'flight_key_urlsafe' in JSON else None
    flight_waypoints_key_urlsafe = JSON.get('flight_waypoints_key_urlsafe') if 'flight_waypoints_key_urlsafe' in JSON else None
        
    flight = Flight(flight_num=flight_num, location=ndb.GeoPt(latitude, longitude), 
        altitude=altitude, speed=speed, temperature=temperature)
    flight_key = update_or_insert_flight(flight, flight_key_urlsafe)

    if (flight_waypoints_key_urlsafe is None):
        flight_waypoints_key, data = insert_flight_waypoints(flight_num, flight_key.urlsafe())
        data['flight_waypoints_key_urlsafe'] = flight_waypoints_key.urlsafe()
    else:
        data = retrieve_next_data(flight_waypoints_key_urlsafe)
    
    if flight_key_urlsafe is None:
        flight_key_urlsafe_to_send = flight_key.urlsafe()
        data['flight_key_urlsafe'] = flight_key_urlsafe_to_send

    return jsonify(data)
Exemplo n.º 4
0
    def setUp(self):
        import datetime
        today = datetime.date.today()

        self.u = User(username='******')
        self.u.save()

        self.baron = Plane(tailnumber="N1234", type='BE-55')
        self.baron.save()

        self.seaplane = Plane(tailnumber="N5678", cat_class=3)
        self.seaplane.save()

        self.local_route = Route.from_string('kvta kvta')

        self.more50nm_route = Route.from_string('kvta kluk')
        self.no_land_more50nm_route = Route.from_string('kvta @kluk kvta')

        self.less50nm_route = Route.from_string('kvta kcmh')
        self.no_land_less50nm_route = Route.from_string('kvta @kcmh kvta')

        self.f = Flight(total=11.0,
                        pic=10.0,
                        date=today,
                        route=self.local_route)
Exemplo n.º 5
0
    def _create_flights(self, data: List[dict]) -> List['Flight']:
        """Создает список экземпляров Flight на основе данных из словаря."""
        flights = []
        for f_dct in data:
            # Перевозчик.
            carrier = self._carriers.get(f_dct['carrier_id'])
            if carrier is None:
                carrier = self._create_carrier(carrier_id=f_dct['carrier_id'],
                                               name=f_dct['carrier'])
            # Аэропорты.
            source = self._carriers.get(f_dct['source'])
            destination = self._carriers.get(f_dct['destination'])
            if source is None:
                source = self._create_airport(code=f_dct['source'])
            if destination is None:
                destination = self._create_airport(code=f_dct['destination'])

            flight = Flight(carrier=carrier,
                            number=f_dct['flight_number'],
                            source=source,
                            destination=destination,
                            departure_timestamp=f_dct['departure_timestamp'],
                            arrival_timestamp=f_dct['arrival_timestamp'],
                            trip_class=f_dct['trip_class'],
                            number_of_stops=f_dct['number_of_stops'],
                            fare_basis=f_dct['fare_basis'],
                            warning_text=f_dct['warning_text'] or '',
                            ticket_type=f_dct['ticket_type'])

            flights.append(flight)

        return flights
Exemplo n.º 6
0
def edit_flight(request, page):

    url = logbook_url(request.display_user, page)

    if not request.POST:
        return HttpResponseNotAllowed("method not allowed")

    profile, c = Profile.objects.get_or_create(user=request.display_user)
    plane_widget = proper_plane_widget(profile)

    flight_id = request.POST['id']
    flight = Flight(pk=flight_id, user=request.display_user)

    form = forms.PopupFlightForm(request.POST,
                                 plane_widget=plane_widget,
                                 user=request.display_user,
                                 instance=flight,
                                 prefix="new")

    if form.is_valid() and request.display_user.username != 'ALL':
        form.save()

        from backup.models import edit_logbook
        edit_logbook.send(sender=request.display_user, page=page)

        return HttpResponseRedirect(url)

    return logbook(request, form=form, fail="edit")
Exemplo n.º 7
0
def backend():
    if request.method == "POST":
        flight = request.form["flight"]
        destination = request.form["destination"]
        check_in = datetime.strptime(request.form['check_in'], '%d-%m-%Y %H:%M %p')
        depature = datetime.strptime(request.form['depature'], '%d-%m-%Y %H:%M %p')
        status = request.form["status"]

        new_flight = Flight(flight, destination, depature, check_in, status)
        db_session.add(new_flight)
        db_session.commit()

        data = {
            "id": new_flight.id,
            "flight": flight,
            "destination": destination,
            "check_in": request.form['check_in'],
            "depature": request.form['depature'],
            "status": status}
            
        pusher_client.trigger('table', 'new-record', {'data': data })

        return redirect("/backend", code=302)
    else:
        flights = Flight.query.all()
        return render_template('backend.html', flights=flights)
Exemplo n.º 8
0
def main():
    f = open('flights.csv')
    reader = csv.reader(f)
    for origin, destination, duration in reader:
        flight = Flight(origin=origin,
                        destination=destination,
                        duration=duration)
        db.session.add(flight)
        print(
            f"Added flight from {origin} to {destination} lasting {duration}.")
    db.session.commit()
Exemplo n.º 9
0
 def add_Flight():
     try:
         data = json.loads(request.data)
         flight = Flight(SpaceShip=data['spaceship'],
                         Station=data['station'],
                         LaunchingPad=data['launchingpad'],
                         LaunchingDate=data['launchingdate'])
         Flight.insert(flight)
     except BaseException:
         print('aborted')
         abort(422)
     return paginate_flights()
Exemplo n.º 10
0
def delete_flight(request, page):
    url = logbook_url(request.display_user, page)

    if not request.POST:
        return HttpResponseNotAllowed("method not allowed")

    if request.display_user.username != 'ALL':
        flight_id = request.POST['id']
        Flight(pk=flight_id, user=request.display_user).delete()

        from backup.models import edit_logbook
        edit_logbook.send(sender=request.display_user, page=page)

    return HttpResponseRedirect(url)
Exemplo n.º 11
0
    def setUp(self):
        self.p = Plane(tailnumber="N444444", cat_class=4, type="TYPE")
        self.p.save()

        self.u = User(username='******')
        self.u.save()

        self.f = Flight(
            plane=self.p,
            route=Route.from_string('mer-lga'),
            user=self.u,
            date='2009-01-05',
            total=10.0,
        )
        self.f.save()
Exemplo n.º 12
0
def mainExpedia():
    print "Gil<3"
    results, contentJson = askFromExpedia()
    destinationInTimeline = findDestination(contentJson, results)
    airwayInTimeline = findAirway(contentJson, results)
    flightIdInTimeline = findAirway(contentJson, results)
    info = {
        "source" : contentJson['legs'][results]['departureLocation']['airportCode'],
        "destination" : destinationInTimeline['arrivalAirport']['code'],
        "start_date" : contentJson['legs'][results]['departureTime']['date'],
        "end_date" : contentJson['legs'][results]['arrivalTime']['date'],
        "price" : contentJson['legs'][results]['price']['exactPrice'],
        "airway" : airwayInTimeline['carrier']['airlineName'],
        "flight_id" : flightIdInTimeline['carrier']['flightNumber']
    }
    return Flight(info["source"], info["destination"], info["start_date"], info["end_date"], info["price"], info["airway"], info["flight_id"])
Exemplo n.º 13
0
def main():
    f = open("flights.csv")
    reader = csv.reader(f)
    for origin, destination, duration in reader:
        #     db.execute("INSERT INTO flights (origin, destination, duration) VALUES (:origin, :destination, :duration)",
        #                 {"origin": origin, "destination": destination, "duration": duration})
        #     print(f"Added flight from {origin} to {destination} lasting {duration} minutes.")
        # db.commit()
        flight = Flight(origin=origin,
                        destination=destination,
                        duration=duration)
        db.session.add(flight)
        print(
            f"Added flight from {origin} to {destination} lasting {duration} minutes."
        )
    db.session.commit()
Exemplo n.º 14
0
  def _parseFlightInfo(self, soup):
    """ For each reservation, get the date, and each flight leg with airport code,
        departure and arrival times
    """
    dlog("line 445")
    flight = Flight()
    dlog(flight)
    # Get flight reservation date from first flight leg
    flight_date_str = FindByTagClass(soup, 'span', 'itinerary-table--summary-travel-date').string.strip()
    day = date(*time_module.strptime(flight_date_str, '%A, %B %d, %Y')[0:3])
    dlog("Reservation Date: " + str(day))

    # Each flight leg is represented in a row in the HTML table.
    # Each row includes arrival and departure times and flight number.
    dlog("line 451")
    for tr in soup.find_all("td", recursive=False):
      dlog(tr)
      flight_leg = FlightLeg()
      dlog(flight_leg)
      flight.legs.append(flight_leg)
      dlog("Flight Legs: " + str(flight_leg))

      # Get flight number
      parent = FindByTagClass(tr, 'span', 'itinerary-table--segment-flight-number')
      flight_leg.flight_number = strip_tags(unicode(parent.strong))
      print "Found flight", flight_leg.flight_number
      dlog("Flight Number: " + str(flight_leg.flight_number))

      dlog("line 469")
      # List of arrival and departure details for each airport
      flight_leg_soup1 = tr.find('table', 'airProductItineraryTable airItineraryTable')
      dlog("got flight_leg_soup1")
      flight_leg_soup = flight_leg_soup1.find_all('tr')
      dlog("got flight_leg_soup")
      dlog("Parsing Departure:")
      flight_leg.depart = self._parseFlightLegDetails(day, flight_leg_soup[0])
      dlog("Parsing Arrival:")
      flight_leg.arrive = self._parseFlightLegDetails(day, flight_leg_soup[1])

      if flight_leg.arrive.dt_utc < flight_leg.depart.dt_utc:
        flight_leg.arrive.dt = flight_leg.arrive.tz.normalize(
          flight_leg.arrive.dt.replace(day = flight_leg.arrive.dt.day+1))
        flight_leg.arrive.dt_utc = flight_leg.arrive.dt.astimezone(utc)
        flight_leg.arrive.dt_formatted = DateTimeToString(flight_leg.arrive.dt)
        flight_leg.arrive.dt_utc_formatted = DateTimeToString(flight_leg.arrive.dt_utc)

    return flight
Exemplo n.º 15
0
def addflight():
    if request.method == 'POST':
        origin = request.form.get('origin')
        destination = request.form.get('destination')
        try:
            duration = int(request.form.get('duration'))
        except ValueError:
            duration = None
        if origin and destination and duration:
            flight = Flight(origin=origin,
                            destination=destination,
                            duration=duration)
            db.session.add(flight)
            db.session.commit()
            return redirect(url_for('flights'))
        else:
            return redirect(url_for('addflight'))
    return render_template('addflight.html')
def addflight():

    if 'username' not in session:
        return redirect(url_for('upcoming'))
    form = FlightForm()
    if (request.method == 'POST'):
        if not form.validate_on_submit():

            return render_template('addflight.html', form=form)
        else:
            arrival_date_time = str(form.arrival_date.data) + " " + str(
                form.arrival_time.data)
            departure_date_time = str(form.departure_date.data) + " " + str(
                form.departure_time.data)
            newflight = Flight(form.airline_name.data, form.flight_num.data,
                               form.departure_airport.data,
                               departure_date_time, form.arrival_airport.data,
                               arrival_date_time, form.price.data,
                               form.status.data, form.airplane_id.data)
            return redirect(url_for('upcoming'))
    elif (request.method == 'GET'):
        return render_template('addflight.html', form=form)
Exemplo n.º 17
0
    db = Database(heroku=True)

  db.create_all()

  puts('Adding a reservation...')
  try:
    res = Reservation('Bob', 'Smith', '999999', '*****@*****.**')
    db.Session.add(res)
    db.Session.commit()
  except Exception, e:
    record_error('Failed on adding the reservation', e)

  puts('Adding a flight...')
  try:
    flights = []
    flights.append(Flight())
    flights[0].sched_time = 10.0
    flights.append(Flight())
    res.flights = flights
    db.Session.commit()
  except Exception, e:
    record_error('Failed on adding the flight', e)

  puts('Adding a flight leg...')
  try:
    res.flights[0].legs.append(FlightLeg())
    res.flights[1].legs.append(FlightLeg())
    res.flights[0].legs[0].flight_number = "1234"
    db.Session.commit()
  except Exception, e:
    record_error('Failed on adding a flight leg', e)
Exemplo n.º 18
0
 def setUpFlight(self, reservation):
     flights = []
     flights.append(Flight())
     flights[0].sched_time = 10.0
     flights.append(Flight())
     reservation.flights = flights
Exemplo n.º 19
0
        driver.implicitly_wait(2)
        resultado = driver.find_element_by_css_selector(final_class)

        driver.quit()
        valor_exibicao = resultado.text
        valor_processado = valor_exibicao.split("R$")
        valor_processado = valor_processado[1]
        valor_processado = re.sub('[^0-9]+', '', valor_processado)

        landing = Place.objects.filter(id=int(destino[0])).get()
        schedule = Schedule.objects.filter(id=int(scheduleid)).get()

        if schedule:
            notify_price_range_to_user(valor_processado, schedule)

        fly = Flight()
        fly.schedule = schedule
        fly.departure = departure
        fly.landing = landing
        fly.price = valor_processado
        fly.departure_date = config_dia_inicio
        fly.landing_date = config_dia_fim
        fly.link = url
        fly.save()

        driver.quit()
    except NoSuchElementException, e:
        notfound_class = '.' + class_splited[0] + '-Pb-e'
        resultado = driver.find_element_by_css_selector(notfound_class)
        for ne in nao_existe:
            if str(ne) == str(destino[1]):
Exemplo n.º 20
0
                         flightObj['estArrivalAirport']))
    for temp in validFlightList:
        if temp.icao == flightObj['icao24']:
            #print(temp.icao)

            try:
                #print('{}, {}'.format(flightObj['estDepartureAirport'], flightObj['estArrivalAirport']))
                dAirport = db.session.query(Airport).filter(
                    func.lower(Airport.icao24) == func.lower(
                        flightObj['estDepartureAirport'])).one()
                aAirport = db.session.query(Airport).filter(
                    func.lower(Airport.icao24) == func.lower(
                        flightObj['estArrivalAirport'])).one()
                flight = Flight(
                    flight_number=callsign,
                    departing_airport=dAirport,
                    arriving_airport=aAirport,
                    depature_time=flightObj['firstSeen'],
                    expected_arrival_time=flightObj['lastSeen'],
                    latitude=temp.lat,
                    longitude=temp.lon,
                    delayed=temp.on_g,
                    true_tracks=temp.true_t(float),
                    last_updated=datetime.datetime.now().timestamp())
                db.session.add(flight)
            except Exception as e:
                pass
                #print('ERROR: Unable to add flight for the state ' + str(flightObj) + ': ' + str(e))

            db.session.commit()