|
| 1 | +import requests |
| 2 | +from flight_data import FlightData |
| 3 | + |
| 4 | +TEQUILA_ENDPOINT = "https://tequila-api.kiwi.com" |
| 5 | +TEQUILA_API_KEY = "********************************" |
| 6 | + |
| 7 | + |
| 8 | +class FlightSearch: |
| 9 | + |
| 10 | + def get_destination_code(self, city_name): |
| 11 | + location_endpoint = f"{TEQUILA_ENDPOINT}/locations/query" |
| 12 | + headers = {"apikey": TEQUILA_API_KEY} |
| 13 | + query = {"term": city_name, "location_types": "city"} |
| 14 | + response = requests.get(url=location_endpoint, headers=headers, params=query) |
| 15 | + results = response.json()["locations"] |
| 16 | + code = results[0]["code"] |
| 17 | + return code |
| 18 | + |
| 19 | + def check_flights(self, origin_city_code, destination_city_code, from_time, to_time): |
| 20 | + headers = {"apikey": TEQUILA_API_KEY} |
| 21 | + query = { |
| 22 | + "fly_from": origin_city_code, |
| 23 | + "fly_to": destination_city_code, |
| 24 | + "date_from": from_time.strftime("%d/%m/%Y"), |
| 25 | + "date_to": to_time.strftime("%d/%m/%Y"), |
| 26 | + "nights_in_dst_from": 7, |
| 27 | + "nights_in_dst_to": 28, |
| 28 | + "flight_type": "round", |
| 29 | + "one_for_city": 1, |
| 30 | + "max_stopovers": 0, |
| 31 | + "curr": "GBP" |
| 32 | + } |
| 33 | + |
| 34 | + response = requests.get( |
| 35 | + url=f"{TEQUILA_ENDPOINT}/v2/search", |
| 36 | + headers=headers, |
| 37 | + params=query, |
| 38 | + ) |
| 39 | + try: |
| 40 | + data = response.json()["data"][0] |
| 41 | + except IndexError: |
| 42 | + query["max_stopovers"] = 1 |
| 43 | + response = requests.get( |
| 44 | + url=f"{TEQUILA_ENDPOINT}/v2/search", |
| 45 | + headers=headers, |
| 46 | + params=query, |
| 47 | + ) |
| 48 | + data = response.json()["data"][0] |
| 49 | + pprint(data) |
| 50 | + flight_data = FlightData( |
| 51 | + price=data["price"], |
| 52 | + origin_city=data["route"][0]["cityFrom"], |
| 53 | + origin_airport=data["route"][0]["flyFrom"], |
| 54 | + destination_city=data["route"][1]["cityTo"], |
| 55 | + destination_airport=data["route"][1]["flyTo"], |
| 56 | + out_date=data["route"][0]["local_departure"].split("T")[0], |
| 57 | + return_date=data["route"][2]["local_departure"].split("T")[0], |
| 58 | + stop_overs=1, |
| 59 | + via_city=data["route"][0]["cityTo"] |
| 60 | + ) |
| 61 | + return flight_data |
| 62 | + else: |
| 63 | + flight_data = FlightData( |
| 64 | + price=data["price"], |
| 65 | + origin_city=data["route"][0]["cityFrom"], |
| 66 | + origin_airport=data["route"][0]["flyFrom"], |
| 67 | + destination_city=data["route"][0]["cityTo"], |
| 68 | + destination_airport=data["route"][0]["flyTo"], |
| 69 | + out_date=data["route"][0]["local_departure"].split("T")[0], |
| 70 | + return_date=data["route"][1]["local_departure"].split("T")[0] |
| 71 | + ) |
| 72 | + |
| 73 | + return flight_data |
0 commit comments