def month(request, year, month): year = int(year) month = int(month) # Get months: months = set() Flight.clear_filter(request.user) flights = Flight._filtered.filter(date__year=year) for f in flights: months.add(f.date.month) months = list(months) months.sort(lambda x, y: y - x) # reverse numerical month_hour_data = [] for m in months: hours = total_hours(flights.filter(date__month=m)) month_hour_data.append(Month_Hours(m, hours)) # flights = Flight.objects.filter(date__year=year, date__month=month).order_by('-date','-id') flights = flights.filter(date__month=month).order_by('-date', '-id') label = '%d.%d' % (month, year) context = { 'flights': flights, 'flights_label': label, 'year': year, 'month': month, 'month_hour_data': month_hour_data } return render(request, 'logbook/month.html', context)
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)
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)
def year(request, year): year = int(year) # Get months: months = set() Flight.clear_filter(request.user) flights = Flight._filtered.filter(date__year=year) for f in flights: months.add(f.date.month) months = list(months) months.sort(lambda x, y: y - x) # reverse numerical month_hour_data = [] for m in months: hours = total_hours(flights.filter(date__month=m)) month_hour_data.append(Month_Hours(m, hours)) # Get flights for last month with non-empty entries: month = months[0] # flights = Flight._filtered.filter(date__year=year, date__month=month).order_by('-date','-id') flights = flights.filter(date__month=month).order_by('-date', '-id') flights_label = str(month) + '.' + str(year) context = { 'flights': flights, 'flights_label': flights_label, 'year': year, 'month_hour_data': month_hour_data } return render(request, 'logbook/year.html', context)
def reset_database(request): Flight.objects.all().delete() Distance.objects.all().delete() num_trip = 0 num_dis = 0 for trip_wrapper in base_trips.flights['flights']: trip = trip_wrapper['flight'] new_flight = Flight() new_flight.build_from_json(trip) new_flight.save() num_trip += 1 if trip['round-trip'] == 'True': new_return_flight = Flight() new_return_flight.build_return_flight(new_flight, trip['return']) new_return_flight.save() num_trip += 1 keys = [trip['origin'], trip['destination']] keys.sort() d, created = Distance.objects.get_or_create(point_a = keys[0], point_b = keys[1]) if created: d.distance_km = haversine( new_flight.origin_long, new_flight.origin_lat, new_flight.dest_long, new_flight.dest_lat) d.save() num_dis += 1 recap = 'num of entries added: %d <br />' % num_trip recap += 'num of distances created: %d <br />' % num_dis return HttpResponse(recap)
def delete_flight(id): print('delete flight') try: flight = Flight.query.get(id) Flight.delete(flight) except BaseException: print("aborted") abort(404) finally: return jsonify({'Deleted flight': id, 'success': True})
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()
def post(self): going_gol, back_gol = gol_parse(gol_data()) going_tam, back_tam = tam_parse(tam_data()) s = Survey() s.date = datetime.now() for flight in going_gol: f = Flight(flight, True) f.company = 'GOL' s.flights.append(f) for flight in back_gol: f = Flight(flight, False) f.company = 'GOL' s.flights.append(f) for flight in going_tam: f = Flight(flight, True) f.company = 'TAM' s.flights.append(f) for flight in back_tam: f = Flight(flight, False) f.company = 'TAM' s.flights.append(f) db.session.add(s) db.session.commit() return s.serialize
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()
def index(request): # Get years: years = set() Flight.clear_filter(request.user) flights = Flight._filtered for f in flights: years.add(f.date.year) years = list(years) years.sort(lambda x, y: y - x) # reverse numerical year_hour_data = [] for y in years: hours = total_hours(flights.filter(date__year=y)) hours = '%0.f' % hours year_hour_data.append(Year_Hours(y, hours)) # Get recent entries: recent_entries = flights.order_by( '-id')[:NUM_RECENT_ENTRIES_DISPLAYED_HOMEPAGE] # Get summary information: duration_sum = Flight.duration_sum() last_90 = Flight._filtered.filter(date__range=(today() - datetime.timedelta(90), today())) last_30 = Flight._filtered.filter(date__range=(today() - datetime.timedelta(90), today())) hours_in_last_90 = sum([f.duration for f in last_90]) hours_in_last_30 = sum([f.duration for f in last_30]) landings = Flight.total_landings_sum() landings_in_last_90 = sum([f.total_landings() for f in last_90]) landings_in_last_30 = sum([f.total_landings() for f in last_30]) context = { 'flights': recent_entries, 'flights_label': 'Recent entries', 'year_hour_data': year_hour_data, 'today': today, 'duration_sum': duration_sum, 'hours_in_last_90': hours_in_last_90, 'hours_in_last_30': hours_in_last_30, 'landings': landings, 'landings_in_last_90': landings_in_last_90, 'landings_in_last_30': landings_in_last_30, 'user': request.user } return render(request, 'logbook/index.html', context)
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
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)
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")
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)
def dispatch(request): action = request.POST['action'] if action == 'Summarize by make and model': context = {'make_and_models': Make_and_model.objects.all()} return render(request, 'logbook/make_model_choose.html', context) elif action == 'Summarize by equipment complexity': context = {'equipments': Equipment.objects.all()} return render(request, 'logbook/equipment_choose.html', context) elif action == 'Summarize by date range': return HttpResponseRedirect(reverse('date_range_choose')) else: Flight.clear_filter(request.user) context = { 'Flight': Flight, 'title': 'Comprehensive summary of all flying:' } return render(request, 'logbook/summary.html', context)
def action(self): #Get current flight obj = self.flights[self.flighti] self.flighti += 1 #Load data from raw object flight = Flight() flight.aircraft_id = obj['ac_id'] flight.aircraft_type = obj['ac_type'] flight.latitude = str(obj['lat'])[:-4] + '.' + str(obj['lat'])[-4:] flight.longitude = str(obj['long'])[:-4] + '.' + str(obj['long'])[-4:] flight.speed = obj['speed'] flight.altitud = obj['altitude'] flight.heading = obj['heading'] flight.center = obj['center'] flight.sector = obj['sector'] #Write in websocket self.write_message(md.get_data(flight.latitude, flight.longitude))
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])
def get_single_flight_info(flight_container): flight_info = {} flight_info['airlines'] = {} try: flight_info['airlines']["airline_logo"] = ( flight_container.findChild("div", { "class": "leg-carrier" }).findChild("img")['src']) except: flight_info['airlines']["airline_logo"] = ( flight_container.findChild("div", { "class": "section carriers" }).findChild('img')['src']) flight_info['airlines']["name"] = (flight_container.findChild( "div", { "class": "section times" }).findChild("div", { "class": "bottom" }).text.strip()) # info string is the arialabel like below # "Depart Leg: American Airlines, SFO 11:28 pm - JFK 3:17 pm. Select to show all results with this leg" info_string = flight_container.findChild( "input", {"name": "specleg"})['aria-label'] origin_idx = info_string.index(",") flight_info["airport_origin"] = info_string[origin_idx + 2:origin_idx + 5] depart_time_idx = origin_idx + 6 divider_idx = info_string.index("-") flight_info["takeoff_time"] = info_string[depart_time_idx:divider_idx - 1] destination_idx = divider_idx + 2 flight_info["airport_destination"] = info_string[ destination_idx:destination_idx + 3] landing_time_idx = destination_idx + 4 period_idx = info_string.index(".") flight_info["landing_time"] = info_string[landing_time_idx:period_idx] connections = flight_container.findChild("div", { "class": "section stops" }).text.strip().split("\n\n\n") flight_info["connections"] = connections[1:] flight_info["duration"] = flight_container.findChild( "div", { "class": re.compile("section duration") }).findChild("div", { "class": "top" }).text.strip() return Flight.fromdict(flight_info)
def create(request): # Get recent entries: Flight.clear_filter(request.user) recent = Flight._filtered.order_by('-id')[:NUM_RECENT_ENTRIES_DISPLAYED] # Create a form and populate it : if Flight._filtered.count() == 0: form = FlightForm() else: form = FlightForm(instance=Flight._filtered.last()) # Display the form to the user for editing and possible saving: context = { 'flights': recent, 'flights_label': 'Recent entries', 'form': form, 'message': 'Unsaved new entry: ', 'entry_number': 0 } return render(request, 'logbook/flight.html', context)
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()
def get_cheapest_flight(source, destination, start_date, end_date): key = "%s:%s:%s:%s" % (source, destination, start_date, end_date) cached_cheapest_flight = Redis.get_from_db(key) if cached_cheapest_flight is None: cheapest_flight = mainExpedia() value = json.dumps(cheapest_flight.to_dict()) Redis.add_to_db(key, value) print "from expedia" return cheapest_flight else: print "from redis" return Flight.from_dict(json.loads(cached_cheapest_flight))
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()
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)
def date_range_choose(request): if request.method == 'POST': form = DateRangeForm(request.POST) if form.is_valid(): Flight.clear_filter(request.user) begin = form.cleaned_data['begin'] # in datetime format end = form.cleaned_data['end'] Flight._filtered = Flight._filtered.filter(date__range=(begin, end)) begin = begin.strftime('%m.%d.%Y') # as string end = end.strftime('%m.%d.%Y') return HttpResponseRedirect( reverse('date_range', args=(begin, end))) else: message = 'Something is wrong. Please check the date format is mm.dd.yy' context = {'form': form, 'message': message} return render(request, 'logbook/date_range_choose.html', context) else: today = datetime.date.today() ninety_days_ago = today - datetime.timedelta(90) form = DateRangeForm({'begin': ninety_days_ago, 'end': today}) message = 'Enter dates in the format mm.dd.yy (default is for last 90 days).' context = {'form': form, 'message': message} return render(request, 'logbook/date_range_choose.html', context)
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()
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"])
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
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)
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)
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]):
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()
def logbook(request, page=0, form=None, fail=None): """ Prepare the Logbook page """ if page == "0": url = reverse("logbook", kwargs={"username": request.display_user}) return HttpResponseRedirect(url) auto_button, c = AutoButton.objects.get_or_create( user=request.display_user) cols, c = Columns.objects.get_or_create(user=request.display_user) profile, c = Profile.objects.get_or_create(user=request.display_user) ################## custom filter form ######################## from custom_filter import make_filter_form ## filter form is created dynamically because each user has different planes ## so those dropdowns will be different FilterForm = make_filter_form(request.display_user) ff = FilterForm() ############################################################## all_flights = Flight.objects\ .user(request.display_user, disable_future=True)\ .order_by('date', 'id') filtered_flights = all_flights.select_related() total_sign = "Overall" if request.GET: ff = FilterForm(request.GET) filtered_flights = filtered_flights.custom_logbook_view(ff) ## split it to get just the part after the '?', ignore the part before get = "?" + request.get_full_path().split("?")[1] total_sign = "Filter" ############## google maps and google earth filter below ################ earth = request.GET.get('earth') maps = request.GET.get('maps') if earth == 'true': routes = Route.objects.filter(flight__in=filtered_flights) response = qs_to_time_kmz(routes) response['Content-Disposition'] = 'attachment; filename=filter.kmz' return response if maps == 'true': url = "http://maps.google.com/?q=http://flightlogg.in/%s/logbook.html%s" get = get.replace('maps=true', "earth=true").replace('&', '%26') return HttpResponseRedirect(url % (request.display_user.username, get)) ############### pagination stuff below ############################ before_block, after_block, page_of_flights = \ Flight.make_pagination(filtered_flights, profile, int(page)) #only make the page table if there are more than one pages overall do_pagination = page_of_flights.paginator.num_pages > 1 if not form: plane_widget = proper_plane_widget(profile) form = forms.PopupFlightForm(plane_widget=plane_widget, prefix="new", user=request.display_user) else: ## set this variable so we know which popup to prepare to enter the ## failed form data edit_or_new = fail return locals()
class ColumnsTest(TestCase): fixtures = ['airport/test-fixtures/ohio.json', 'airport/test-fixtures/test-region.json', 'airport/test-fixtures/test-country.json'] 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) def test_cat_class_columns(self): """ Tests that all the columns that deal with category/class output the correct value """ # multi engine land ######################################################### self.f.plane = self.baron self.f.save() self.failUnlessEqual(self.f.column('single'), "") self.failUnlessEqual(self.f.column('m_pic'), "10.0") self.failUnlessEqual(self.f.column('m_t'), "") # multi-sea local ######################################################### self.f.plane = self.seaplane self.f.save() self.failUnlessEqual(self.f.column('single'), "11.0") self.failUnlessEqual(self.f.column('m_pic'), "") self.failUnlessEqual(self.f.column('m_t'), "") def test_local_route_columns(self): """ Tests the columns that depend on the properties of the route when the route is a local flight """ self.f.route = self.local_route # vta vta self.f.save() self.failUnlessEqual(self.f.column('p2p'), "") self.failUnlessEqual(self.f.column('atp_xc'), "") self.failUnlessEqual(self.f.column('max_width'), "") self.failUnlessEqual(self.f.column('line_dist'), "") def test_less_50_nm_route(self): """ Tests the columns that depend on the properties of the route when the route is greater than 50nm """ self.f.route = self.less50nm_route # vta cmh self.f.save() self.failUnlessEqual(self.f.column('p2p'), "11.0") self.failUnlessEqual(self.f.column('atp_xc'), "") self.failUnlessEqual(self.f.column('max_width'), "19.9") self.failUnlessEqual(self.f.column('line_dist'), "19.9") self.f.route = self.no_land_less50nm_route # vta @cmh vta self.f.save() self.failUnlessEqual(self.f.column('p2p'), "") self.failUnlessEqual(self.f.column('atp_xc'), "") self.failUnlessEqual(self.f.column('max_width'), "19.9") self.failUnlessEqual(self.f.column('line_dist'), "39.7") def test_more_50_nm_route(self): """ Tests the columns that depend on the properties of the route when the route is less than 50nm """ self.f.route = self.no_land_more50nm_route # vta @luk vta self.f.save() self.failUnlessEqual(self.f.column('p2p'), "") self.failUnlessEqual(self.f.column('atp_xc'), "11.0") self.failUnlessEqual(self.f.column('max_width'), "106.5") self.failUnlessEqual(self.f.column('line_dist'), "212.5") self.f.route = self.more50nm_route # vta luk self.f.save() self.failUnlessEqual(self.f.column('p2p'), "11.0") self.failUnlessEqual(self.f.column('atp_xc'), "11.0") self.failUnlessEqual(self.f.column('max_width'), "106.5") self.failUnlessEqual(self.f.column('line_dist'), "106.2")
def setUpFlight(self, reservation): flights = [] flights.append(Flight()) flights[0].sched_time = 10.0 flights.append(Flight()) reservation.flights = flights
def logbook(request, page=0, form=None, fail=None): """ Prepare the Logbook page """ if page == "0": url = reverse("logbook", kwargs={"username": request.display_user}) return HttpResponseRedirect(url) auto_button,c = AutoButton.objects.get_or_create(user=request.display_user) cols, c = Columns.objects.get_or_create(user=request.display_user) profile,c = Profile.objects.get_or_create(user=request.display_user) ################## custom filter form ######################## from custom_filter import make_filter_form ## filter form is created dynamically because each user has different planes ## so those dropdowns will be different FilterForm = make_filter_form(request.display_user) ff = FilterForm() ############################################################## all_flights = Flight.objects\ .user(request.display_user, disable_future=True)\ .order_by('date', 'id') filtered_flights = all_flights.select_related() total_sign = "Overall" if request.GET: ff = FilterForm(request.GET) filtered_flights = filtered_flights.custom_logbook_view(ff) ## split it to get just the part after the '?', ignore the part before get = "?" + request.get_full_path().split("?")[1] total_sign = "Filter" ############## google maps and google earth filter below ################ earth = request.GET.get('earth') maps = request.GET.get('maps') if earth == 'true': routes = Route.objects.filter(flight__in=filtered_flights) response = qs_to_time_kmz(routes) response['Content-Disposition'] = 'attachment; filename=filter.kmz' return response if maps == 'true': url = "http://maps.google.com/?q=http://flightlogg.in/%s/logbook.html%s" get = get.replace('maps=true', "earth=true").replace('&', '%26') return HttpResponseRedirect(url % (request.display_user.username, get)) ############### pagination stuff below ############################ before_block, after_block, page_of_flights = \ Flight.make_pagination(filtered_flights, profile, int(page)) #only make the page table if there are more than one pages overall do_pagination = page_of_flights.paginator.num_pages > 1 if not form: plane_widget = proper_plane_widget(profile) form = forms.PopupFlightForm(plane_widget=plane_widget, prefix="new", user=request.display_user) else: ## set this variable so we know which popup to prepare to enter the ## failed form data edit_or_new = fail return locals()
class FuelBurnTest(TestCase): 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() def test_regular_fuel_burn(self): self.f.fuel_burn = '98gph' self.f.save() self.failUnlessEqual(self.f.gallons, 980.0) self.failUnlessEqual(self.f.gph, 98) self.f.fuel_burn = '874.5 g' self.f.save() self.failUnlessEqual(self.f.gallons, 874.5) self.failUnlessEqual(self.f.gph, 87.45) def test_conversion(self): """ Test that teh conversion routines are accurate """ self.f.fuel_burn = '10 l' self.f.save() self.failUnlessEqual("%.2f" % self.f.gallons, "%.2f" % 2.64172052) self.f.fuel_burn = '60 pll' self.f.save() self.failUnlessEqual(self.f.gallons, 360) self.f.fuel_burn = '60p' self.f.save() self.failUnlessEqual(self.f.gallons, 408.0) def test_zero_fuel_burn(self): """ Test that the routine can handle fuel burns that are zero and where the time is zero """ self.f.fuel_burn = '0 gph' self.f.save() self.failUnlessEqual(self.f.gallons, 0) self.failUnlessEqual(self.f.gph, 0) self.f.fuel_burn = '56 g' self.f.total = 0 self.f.save() self.failUnlessEqual(self.f.gallons, 56) self.failUnlessEqual(self.f.gph, 0) self.f.fuel_burn = '56 gph' self.f.total = 0 self.f.save() self.failUnlessEqual(self.f.gallons, 0) self.failUnlessEqual(self.f.gph, 56)