-
Notifications
You must be signed in to change notification settings - Fork 1
/
flighthandler.py
359 lines (280 loc) · 10.8 KB
/
flighthandler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import json
import asyncio
import requests
from dateutil import parser
from datetime import datetime
from datetime import timedelta
import time
keys = open('api_keys.txt').read().split("\n")
SKY_API_KEY = keys[0]
GEO_API_KEY = keys[1]
URI = "https://www.skyscanner.net/g/chiron"
# access root of request, get client data
# replace this with actual ip
IP = "147.83.201.97"
# hardcoded for now
LOCALE_CODE = "en-GG"
CURRENCY_CODE = "EUR"
def getuserdata(ip):
try:
resp = requests.get("http://api.ipstack.com/"+ip+"?access_key="+GEO_API_KEY).json()
return resp["country_code"], resp["country_name"], resp["city"], float(resp["latitude"]), float(resp["longitude"])
except:
return "ES", "Spain", "Barcelona", 41.394378662109375, 2.1131200790405273
COUNTRY_CODE, COUNTRY_NAME, CITY, LAT, LON = getuserdata(IP)
# gets cheapest flights based on the parameters given
def get_flight(from_city, to_city, from_date, to_date, country, currency, locale):
print(URI + "/api/v1/flights/browse/browsequotes/v1.0/"
+ country + "/"
+ currency + "/"
+ locale + "/"
+ from_city + "/"
+ to_city + "/"
+ from_date + "/"
+ to_date)
response = requests.get(URI + "/api/v1/flights/browse/browsequotes/v1.0/"
+ country + "/"
+ currency + "/"
+ locale + "/"
+ from_city + "/"
+ to_city + "/"
+ from_date + "/"
+ to_date,
headers={
"api-key" : SKY_API_KEY,
"Accept" : "application/json"
}
).json()
return response
# get locales supported by skyscanner
def get_locales():
return requests.get(URI + "/api/v1/localisation/reference/v1.0/locales",
headers={
"api-key" : SKY_API_KEY,
"Accept" : "application/json"
}).json()
# get countries supported by skyscanner and format them in a dictionary accessible by country name
def get_country(locale):
resp = requests.get(URI + "/api/v1/localisation/reference/v1.0/countries/" + locale,
headers={
"api-key" : SKY_API_KEY,
"Accept" : "application/json"
}).json()
res = {}
for e in resp["Countries"]:
res[e["Name"]] = e["Code"]
return res
# get currencies
def get_currencies():
"""
{
"Code": "EUR",
"Symbol": "€",
"ThousandsSeparator": ".",
"DecimalSeparator": ",",
"SymbolOnLeft": false,
"SpaceBetweenAmountAndSymbol": true,
"RoundingCoefficient": 0,
"DecimalDigits": 2
}
"""
return requests.get(URI + "/api/v1/localisation/reference/v1.0/currencies",
headers = {
"api-key" : SKY_API_KEY
}).json()
# get an autocompleted place from parameters and a query.
def get_places(country, currency, locale, query):
return requests.get(URI + "/api/v1/places/autosuggest/v1.0/"
+ country + "/"
+ currency + "/"
+ locale
+ "?query=" + query,
headers={
"api-key" : SKY_API_KEY
} ).json()["Places"]
# put all that shit together and just get some flights for a specified date.
def get_cheapest_quotes(start, end, when="anytime", direct=False):
# TODO: add direct filter
country = get_country(LOCALE_CODE)[COUNTRY_NAME]
_start = get_places(country, CURRENCY_CODE, LOCALE_CODE, start)[0]["PlaceId"]
_end = get_places(country, CURRENCY_CODE, LOCALE_CODE, end)[0]["PlaceId"]
print(_start)
print(_end)
flights = get_flight(from_city=_start,
to_city=_end,
from_date=when,
to_date="",
country=country,
currency=CURRENCY_CODE,
locale=LOCALE_CODE)
return flights
def get_session(country, from_place, to_place, leave_date,
passenger_no, carriers):
print(country)
print(CURRENCY_CODE)
print(LOCALE_CODE)
print(from_place)
print(to_place)
print(leave_date)
print(passenger_no)
print(carriers)
# "inboundDate" : return_date,
return requests.post(URI + "/api/v1/flights/search/pricing/v1.0",
headers={
"api-key" : SKY_API_KEY,
"Content-Type" : "application/x-www-form-urlencoded",
"X-Forwarded-For" : IP,
"Accept" : "application/json"
},
data=json.dumps({
"country" : country,
"currency" : CURRENCY_CODE,
"locale" : LOCALE_CODE,
"originPlace" : from_place,
"destinationPlace" : to_place,
"outboundDate" : leave_date.split("T")[0],
"adults" : passenger_no,
"includeCarriers" : carriers
})).json()
def poll_results():
return requests.get(URI + "/api/v1/flights/search/pricing/v1.0")
def bookings(session_id):
return requests.get(URI
+ "/api/v1/flights/search/pricing/v1.0?session_id="
+ session_id
+ "&sortType=price&sortOrder=desc&stops=0",
headers={
"api-key" : SKY_API_KEY,
"Accept" : "application/json"
}
).json()
def filter_bookings(bookings, max_price=500, max_time=600, max_stops=1):
itineraries = bookings["Itineraries"]
legs = bookings["Legs"]
segments = bookings["Segments"]
carriers = bookings["Carriers"]
places = bookings["Places"]
possible_itins = {}
leg_ids = []
_places = {}
_carriers = {}
for place in places:
_places[place["Id"]] = {
"code" : place["Code"],
"name" : place["Name"]
}
for carrier in carriers:
_carriers[carrier["Id"]] = carrier["DisplayCode"]
for itin in itineraries:
prices = itin["PricingOptions"]
for price in prices:
if price["Price"] <= max_price:
possible_itins[itin["OutboundLegId"]] = {
"price": price["Price"],
"uri" : price["DeeplinkUrl"]
}
leg_ids.append(itin["OutboundLegId"])
for leg in legs:
if leg["Id"] in leg_ids:
if (len(leg["Stops"]) <= max_stops) and (int(leg["Duration"]) <= max_time):
possible_itins[leg["Id"]]["duration"] = leg["Duration"]
possible_itins[leg["Id"]]["departure"] = leg["Departure"]
possible_itins[leg["Id"]]["arrival"] = leg["Arrival"]
possible_itins[leg["Id"]]["airports"] = [ leg["OriginStation"] ] + leg["Stops"] + [ leg["DestinationStation"] ]
possible_itins[leg["Id"]]["airports"] = map(lambda x: _places[x]
,possible_itins[leg["Id"]]["airports"])
possible_itins[leg["Id"]]["numbers"] = []
for fn in leg["FlightNumbers"]:
possible_itins[leg["Id"]]["numbers"].append(
_carriers[fn["CarrierId"]]
+ str(fn["FlightNumber"]))
return possible_itins
def get_bookings(start, end, direct=False, when="anytime", passenger_no=1):
country = get_country(LOCALE_CODE)[COUNTRY_NAME]
_start = get_places(country, CURRENCY_CODE, LOCALE_CODE, start)[0]["PlaceId"]
_end = get_places(country, CURRENCY_CODE, LOCALE_CODE, end)[0]["PlaceId"]
quotes = get_flight(from_city=_start,
to_city=_end,
from_date=when,
to_date="",
country=country,
currency=CURRENCY_CODE,
locale=LOCALE_CODE)
# {'QuoteId': 1, 'MinPrice': 78.0, 'Direct': False,
# 'OutboundLeg': {'CarrierIds': [1878],
# 'OriginId': 89023,
# 'DestinationId': 54353,
# 'DepartureDate': '2019-10-22T00:00:00'},
# 'QuoteDateTime': '2019-10-08T12:08:00'}
carrier_ids = []
#for carrier in quotes["Carriers"]:
# carrier_ids.append(str(carrier["CarrierId"]))
quotes = quotes["Quotes"]
minPrice = 1000000
for quote in quotes:
if (quote["MinPrice"] < minPrice
and parser.parse(quote["OutboundLeg"]["DepartureDate"]) > datetime.now() ):
carrier_ids = map(str, quote["OutboundLeg"]["CarrierIds"])
when = quote["OutboundLeg"]["DepartureDate"]
print(carrier_ids)
session_id = get_session(country, _start, _end,
when, passenger_no,
",".join(carrier_ids))
session_id = session_id["session_id"]
print("SESSION ID: ")
print(session_id)
_bookings = bookings(session_id)
filtered = filter_bookings(_bookings)
_filtered = []
for f in filtered:
try:
_filtered.append({
"numbers" : filtered[f]["numbers"],
"airports" : filtered[f]["airports"],
"departure_time" : filtered[f]["departure"],
"arrival_time" : filtered[f]["arrival"],
"price" : int(float(filtered[f]["price"])*100),
"duration" : filtered[f]["duration"],
"uri" : filtered[f]["uri"]
})
except KeyError:
pass
_filtered.sort(key=lambda x: x["price"], reverse=False)
"""
for f in _filtered:
try:
del f["uri"]
print(f)
print("- - - -")
except KeyError:
pass
"""
return _filtered
def get_bookings_both_ways(start, end, direct=False, when="anytime", passenger_no=1):
one_way = get_bookings(start, end, direct, when, passenger_no)
try:
timestamp = time.mktime(datetime.strptime(when, "%Y-%m-%d").timetuple()) + timedelta(days=1).total_seconds()
except ValueError:
timestamp = time.mktime(datetime.strptime(when, "%Y-%m").timetuple()) + timedelta(days=1).total_seconds()
try:
when = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d')
except ValueError:
when = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m')
print("WHEN?")
print(when)
other_way = get_bookings(end, start, direct, when, passenger_no)
return {
"price_pp": one_way[0]["price"] + other_way[0]["price"],
"outbound" : one_way[0],
"return" : other_way[0]
}
print(get_bookings_both_ways(start="Vilnius", end="Edinburgh", direct=False, when="2020-01", passenger_no=1))
# EXAMPLE USAGE:
# get_bookings(start="Vilnius", end="Edinburgh", direct=False, when="2020-01", passenger_no=1)
# MANDATORY FIELDS:
# start - location to fly from
# end - location to fly to
# OPTIONAL FIELDS:
# direct - direct flights only. defaults to False
# when - day or month in which the flight should take place. defaults to anytime
# passenger_no - number of passengers for the flight. defaults to 1