Advertisement
skip420

FlightTracker

Sep 6th, 2021
1,546
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.03 KB | None | 0 0
  1.  
  2.  
  3. # From command line execute following command
  4. # python3 FlightTracker.py
  5.  
  6. import urllib
  7. from urllib.request import urlopen
  8. import json
  9. import sys
  10. import re
  11. import datetime
  12. from datetime import date, time, datetime
  13. #from datetime import datetime, date, time
  14. #import mapping as city
  15. import pickle
  16. from dateutil.rrule import rrule, DAILY
  17.  
  18.  
  19.  
  20. BASE_URL="https://ja.flightaware.com/"
  21.  
  22. class MakeMyTrip(object):
  23.    
  24.     def __init__(self):
  25.         self.url_browse = ""
  26.         self.flights_data = ""
  27.         self.stoppage = ""
  28.         self.arrival_time = ""
  29.         self.trip_json = []
  30.        
  31.     def browse(self, url="", roundtrip=False):
  32.         print(url)
  33.         try:
  34.             self.url_browse = urlopen(url).read().decode('utf-8')
  35.         #except urllib.HTTPError:
  36.         except:
  37.             print('There was an ERROR')
  38.         fil = open("out.txt","w")
  39.         fil.write(self.url_browse)
  40.         fil.close()
  41.         i = 0
  42.         fil = open("out.txt","r")
  43.         if roundtrip:
  44.             json_list = json.loads(fil.read())
  45.             #print json_list#['filterData']
  46.             print("-"*50)
  47.             json_list = json.loads(json_list['fd'])
  48.             return json_list
  49.         for line in fil.readlines():
  50.             i = i+1
  51.             if "flightsData" in line:
  52.                 self.flights_data = line
  53.                 break
  54.         temp_flights_data = self.flights_data.replace("var flightsData = ","").strip()
  55.         temp_flights_data = temp_flights_data[:-1]
  56.         fil = open("out.txt","w")
  57.         fil.write(temp_flights_data)
  58.         fil.close()
  59.         try :
  60.             json_list = json.loads(temp_flights_data)
  61.         except ValueError :
  62.             json_list = 1
  63.         return json_list
  64.    
  65.     def create_json_oneway(self, dump_list):
  66.         for i in range(len(dump_list)):
  67.             temp = '{ "airline" : "' + dump_list[i]['le'][0]['an'] + '"'
  68.             temp = temp + ', "price" : "' + str(dump_list[i]['af']) + '"'
  69.             temp = temp + ', "total_time" : "' + str(dump_list[i]['td']) + '"'
  70.             temp = temp + ', "depart_date" : "' + str(dump_list[i]['le'][0]['fd']) + '"'
  71.             temp = temp + ', "depart_time" : "' + str(dump_list[i]['le'][0]['fdt']) + '"'
  72.             temp_dump_list = dump_list[i]['le']
  73.             for x in range(len(temp_dump_list)):
  74.                 if x == (len(temp_dump_list)-1):
  75.                     temp = temp + ', "arrival_date" : "' + str(temp_dump_list[x]['fa']) + '"'
  76.                     temp = temp + ', "arrival_time" : "' + str(temp_dump_list[x]['fat']) + '"}'
  77.             self.trip_json.append(temp)
  78.         return json.dumps(self.trip_json)
  79.        
  80.     def create_json_roundtrip(self, dump_list):
  81.         #Todo : Complete this function to return the custom JSON as response
  82.         for i in range(len(dump_list)):
  83.             return json.loads(['fd'])
  84.        
  85.     def journey_oneway(self, origin, destination, depart_date, adult=1, children=0, infant=0):
  86.         adult = str(adult) if adult >= 1 else "1"
  87.         children = str(children) if children >= 1 else str(children)
  88.         infant = str(infant) if infant >= 1 else str(infant)
  89.         new_url = BASE_URL + "search/O/O/E/" + adult +"/" + children + "/" + infant + "/S/V0/" + origin + "_" + destination + "_" + depart_date
  90.         return self.browse(new_url)
  91.    
  92.     def journey_roundtrip(self, origin, destination, depart_date, return_date, adult=1, children=0, infant=0):
  93.         new_url = BASE_URL + 'splitRTDataService.json?classType=E&deptDate=' + depart_date + '&fltMap=&fromCity='+ origin + '&noOfAdlts=' + str(adult) + \
  94.         '&noOfChd=' + str(children) + '&noOfInfnt=' + str(infant) + '&returnDate=' + return_date + '&toCity=' + destination + '&tripType=R&tripTypeDup=R'
  95.         return self.browse(new_url, True)
  96.        
  97.     #Todo: Get rid of this method
  98.     def read_line(self):
  99.         flights_data=""
  100.         i = 0
  101.         fil = open("out.txt","r")
  102.         for line in fil.readlines():
  103.             i = i+1
  104.             if "flightsData" in line:
  105.                 flights_data = line
  106.         #print "Total lines",i
  107.         self.format_flights_data(flights_data)
  108.         #self.getFlightTable(flights_data)
  109.        
  110.     #Todo: Get rid of this method
  111.     def format_flights_data(self, flights_data):
  112.         new_flights_data = flights_data.replace("var flightsData = ","").strip()
  113.         new_flights_data = new_flights_data[:-1]
  114.         fil = open("out.txt","w")
  115.         fil.write(new_flights_data)
  116.         fil.close()
  117.         d = new_flights_data
  118.         li = json.loads(d)
  119.         self.create_json_oneway(li)
  120.         #print type(new_flights_data)
  121.            
  122.     def get_extra_detail(self, flights_data):
  123.         #date_size=len(flights_data)
  124.         halt = flights_data[0]['f']
  125.         layover = ""
  126.         for x in range(len(flights_data)):
  127.             halt = halt + u"   \u2708   " + flights_data[x]['t'] + " ( " + flights_data[x]['du'] + " )"
  128.             if x > 0:
  129.                 layover = layover + flights_data[x]['f'] + "  ( " + flights_data[x]['lo'] + " )  "
  130.             if x == (len(flights_data)-1):
  131.                 self.arrival_time = flights_data[x]['fa'] + " " +flights_data[x]['fat']
  132.         print(halt)
  133.         return layover
  134.         #return halt
  135.        
  136.     def print_json(self, l):
  137.        
  138.         tmp_size = len(l)
  139.         for i in range(tmp_size):  
  140.             print("")
  141.             print(u"\033[1m" + l[i]['le'][0]['an'] , u"\033[0m      \u20B9 \033[92m", l[i]['af'], "\033[0m  in  ", l[i]['td'])
  142.             layover=self.get_extra_detail(l[i]['le'])
  143.             #ToDo
  144.             print(l[i]['le'][0]['fd'],  l[i]['le'][0]['fdt'],u"  --->>  ", self.arrival_time)
  145.             print("\tStoppage : ", layover)
  146.             #print "Arrival : ", l[i]['le'][0]['fa'], l[i]['le'][0]['fat']
  147.             print(u"\u2982"*50)
  148.  
  149.  
  150.  #To write the required files into json format
  151.  
  152.     def file_json(self,l,destination, origin , flight_date):
  153.         if l == 1 :
  154.             taken_date = str(datetime.today().date())
  155.             f1.write("Origin" + "," + "Destination" + "," + "Dept_Date" + "," + "Dept_Time" + "," + "Arr_Time" + "," + "Total_Fare" + "," + "Base_Fare" + "," + "Fuel_Fare" + "," + "Airways" + "," + "Available" + "," + "Duration" + "," + "Class_Type" + "," + "Flight Number" + "," + "Flight Code" + "," + "FlightID" + "," + "Hopping" + "," +"Taken" +"\n")
  156.             f1.write(origin + "," + destination + "," + flight_date + "," + "NA" + "," + "NA" + "," + "NA" + "," + "NA" + "," + "NA" + "," + "NA" + "," + "NA" + "," + "NA" + "," + "NA" + ","+ "NA" + "," + "NA" + "," + "NA" + "," + "NA" + ","+ taken_date +"\n")
  157.         else :
  158.             tmp_size = len(l)
  159.             f1.write("Origin" + "," + "Destination" + "," + "Dept_Date" + "," + "Dept_Time" + "," + "Arr_Time" + "," + "Total_Fare" + "," + "Base_Fare" + "," + "Fuel_Fare" + "," + "Airways" + "," + "Available" + "," + "Duration" + "," + "Class_Type" + "," + "Flight Number"+ "," + "Flight Code" + "," + "FlightID" + "," + "Hopping" + "," +"Taken" +"\n")
  160.             for i in range(tmp_size):  
  161.                 airways = l[i]['le'][0]['an']
  162.                 fare = l[i]['af']
  163.                 deptdate = l[i]['le'][0]['dep']
  164.                 depttime = l[i]['le'][0]['fdt']
  165.                 arrtime = l[i]['le'][0]['fat']
  166.                 avail = l[i]['le'][0]['flightFare']['bookingClass']['availability']
  167.                 basefare = l[i]['le'][0]['flightFare']['baseFare']
  168.                 fuel_surcharge = l[i]['le'][0]['flightFare']['fuelSurcharge']
  169.                 duration = l[i]['td']
  170.                 origin = l[i]['le'][0]['o']
  171.                 desti = l[i]['le'][0]['d']
  172.                 class_type = l[i]['le'][0]['cls']
  173.                 flight_number = l[i]['le'][0]['fn']
  174.                 flight_code = l[i]['le'][0]['oc']
  175.                 Flight_ID = l[i]['fi']
  176.                 hopping = l[i]['hff']
  177.  
  178.                 '''
  179.                if hopping == True :
  180.                    arrtime = l[i]['le'][1]['fat']
  181.                else :
  182.                    arrtime = l[i]['le'][0]['fat']
  183.                '''
  184.                 taken_date = str(datetime.today().date())
  185.                
  186.                 f1.write(origin + "," + desti + "," + deptdate + "," + depttime + "," + arrtime + "," + str(fare) + "," + str(basefare) + "," + str(fuel_surcharge) + "," +airways+ "," + avail + ","+duration + "," + class_type + ","+ flight_number + "," + flight_code + ","  + Flight_ID + "," + str(hopping) + "," +str(taken_date)+  "\n")
  187.                
  188.  
  189.  
  190.  
  191.        
  192. if __name__=="__main__":
  193.     print
  194.     print("="*30)
  195.     origin = "BLR"
  196.     destination = "DEL"
  197.    
  198.     #Range of dates in which we want the data
  199.     a = date(2018, 10, 18)  
  200.     b = date(2018, 10, 24)
  201.  
  202.     for dt in rrule(DAILY, dtstart=a, until=b):
  203.         print(dt.strftime("%d-%m-%Y"))
  204.         dept_date = str(dt.strftime("%d-%m-%Y"))
  205.         bro = MakeMyTrip()
  206.         f1=open('buff.csv', 'a')
  207.         bro.file_json(bro.journey_oneway(origin,destination,dept_date), destination, origin , dept_date)
  208.         f1.close()
  209.    
  210.    
  211.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement