-
Notifications
You must be signed in to change notification settings - Fork 0
/
flight_search.py
83 lines (75 loc) · 3.1 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
import requests
from flight_data import FlightData
import os
TEQUILA_ENDPOINT = os.environ.get('TEQUILA_ENDPOINT')
TEQUILA_API_KEY = os.environ.get('TEQUILA_API_KEY')
class FlightSearch:
def get_destination_code(self, city_name):
location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query"
headers = {"apikey": TEQUILA_API_KEY}
query = {"term": city_name, "location_types": "city"}
response = requests.get(url=location_endpoint, headers=headers, params=query)
results = response.json()["locations"]
code = results[0]["code"]
return code
def check_flights(self, origin_city_code, destination_city_code, from_time, to_time):
headers = {"apikey": 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": 28,
"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]
# pprint(data)
except IndexError:
print("in except 1")
query["max_stopovers"] = 1
response = requests.get(
url=f"{TEQUILA_ENDPOINT}/v2/search",
headers=headers,
params=query,
)
try:
data = response.json()["data"][0]
except IndexError:
print("in except 2")
return None
else:
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],
max_stopover=1,
via_city=data["route"][0]["cityTo"]
)
print(f"{flight_data.destination_city}: £{flight_data.price}")
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]
)
print(f"{flight_data.destination_city}: £{flight_data.price}")
return flight_data