-
Notifications
You must be signed in to change notification settings - Fork 0
/
flight_search.py
87 lines (74 loc) · 2.97 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
from pprint import pprint
import requests
from flight_data import FlightData
import datetime
flight_endpoint = "https://tequila-api.kiwi.com"
header = {
"apikey": "iWqm-26D0V_tjhwhaMp9bl512ZV8JdX3"
}
TODAY = datetime.datetime.now()
SIX_MONTHS = TODAY+datetime.timedelta(days=180)
class FlightSearch:
#This class is responsible for talking to the Flight Search API.
def get_code(self, city_name):
details = {
"term": city_name,
"location_types": "city"
}
search_response = requests.get(url=f"{flight_endpoint}/locations/query", params=details, headers=header)
flight_search_data = search_response.json()
details = flight_search_data["locations"]
code = details[0]["code"]
return code
def get_flight_details(self, origin_city, city_code):
details = {
"fly_from": origin_city,
"fly_to": city_code,
"date_from": TODAY.strftime("%d/%m/%Y"),
"date_to": SIX_MONTHS.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"
}
search_response = requests.get(url=f"{flight_endpoint}/v2/search", headers=header, params=details)
try:
data = search_response.json()["data"][0]
except IndexError:
details["max_stopovers"] = 1
response = requests.get(
url=f"{flight_endpoint}/v2/search",
headers=header,
params=details
)
try:
data = response.json()["data"][0]
except IndexError:
return None
else:
flight_details = 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_over=1,
via_city=data["route"][0]["cityTo"]
)
return flight_details
else:
flight_details = 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 f"{city}: £{fare}"
return flight_details