-
Notifications
You must be signed in to change notification settings - Fork 0
/
flight_search.py
85 lines (75 loc) · 3.07 KB
/
flight_search.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
import os
import requests
from flight_data import FlightData
from pprint import pprint
TEQUILA_ENDPOINT = "https://tequila-api.kiwi.com"
class FlightSearch:
def __init__(self):
self.city_codes = []
def get_destination_codes(self, city_names):
print("get destination codes triggered")
location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query"
headers = {"apikey": os.environ["TEQUILA_API_KEY"]}
for city in city_names:
query = {"term": city, "location_types": "city"}
response = requests.get(url=location_endpoint, headers=headers, params=query)
results = response.json()["locations"]
code = results[0]["code"]
self.city_codes.append(code)
return self.city_codes
def check_flights(self, origin_city_code, destination_city_code, from_time, to_time):
print(f"Check flights triggered for {destination_city_code}")
headers = {"apikey": os.environ["TEQUILA_API_KEY"]}
query = {
"fly_from": origin_city_code,
"fly_to": destination_city_code,
"date_from": from_time.strftime("%d/%m/%Y"),
"date_to": to_time.strftime("%d/%m/%Y"),
"nights_in_dst_from": 7,
"nights_in_dst_to": 30,
"flight_type": "round",
"one_for_city": 1,
"max_stopovers": 0,
"curr": "GBP"
}
response = requests.get(
url=f"{TEQUILA_ENDPOINT}/v2/search",
headers=headers,
params=query,
)
try:
data = response.json()["data"][0]
except IndexError:
##########################
query["max_stopovers"] = 1
response = requests.get(
url=f"{TEQUILA_ENDPOINT}/v2/search",
headers=headers,
params=query,
)
data = response.json()["data"][0]
pprint(data)
flight_data = FlightData(
price=data["price"],
origin_city=data["route"][0]["cityFrom"],
origin_airport=data["route"][0]["flyFrom"],
destination_city=data["route"][1]["cityTo"],
destination_airport=data["route"][1]["flyTo"],
out_date=data["route"][0]["local_departure"].split("T")[0],
return_date=data["route"][2]["local_departure"].split("T")[0],
stop_overs=1,
via_city=data["route"][0]["cityTo"]
)
return flight_data
###########################
else:
flight_data = FlightData(
price=data["price"],
origin_city=data["route"][0]["cityFrom"],
origin_airport=data["route"][0]["flyFrom"],
destination_city=data["route"][0]["cityTo"],
destination_airport=data["route"][0]["flyTo"],
out_date=data["route"][0]["local_departure"].split("T")[0],
return_date=data["route"][1]["local_departure"].split("T")[0]
)
return flight_data