这是「Python 100 天」系列第 39 天的学习笔记:Capstone(一):特价机票监控 。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。
今天要解决的问题
从一个 Google 表格读取"想去的城市 + 心理价位",查每个城市未来半年内最便宜的往返机票,低于心理价就发 Telegram 提醒。README 知识点:OOP 架构 、HTTP 请求、Telegram 推送、strftime 填日期。
这是第一个真正的"多文件工程",重点不在语法,而在怎么把一件事拆成四个类 。
一、四个类的分工
1 2 3 4 5 DataManager —— 和表格打交道:读目的地、回写 IATA 代码 FlightSearch —— 和机票接口打交道:城市名 → 机场代码、查最低价 FlightData —— 纯数据:一次航班的所有字段 NotificationManager —— 和 Telegram 打交道:发消息 main.py —— 编排:谁先谁后、什么条件下做什么
判断标准很简单:每个类只跟一个外部系统说话 。这样接口换了(比如把 Telegram 换成邮件),只改一个文件。
二、IATA 代码:为什么需要"翻译"
表格里人写的是 Paris,机票接口要的是 PAR。所以第一次运行要先把城市名批量翻译成代码,再写回表格——之后就不用再翻译了 。这就是 if sheet_data[0]["iataCode"] == "": 这一行的意义:只在"还没填过"时执行。
这种"缓存翻译结果"的模式在工程里到处都是(DNS 缓存、字典表、CDN)。
三、日期计算
1 2 3 4 from datetime import datetime, timedelta tomorrow = datetime.now() + timedelta(days=1) six_month = datetime.now() + timedelta(days=6 * 30)
timedelta 表示"一段时间",加减得到新时间。注意 6*30 是近似半年,严谨写法要用 dateutil.relativedelta(months=6)。
代码全文
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 from datetime import datetime, timedelta from data_manager import DataManager from flight_search import FlightSearch from notification_manager import NotificationManager data_manager = DataManager() sheet_data = data_manager.get_destination_data() flight_search = FlightSearch() notification_manager = NotificationManager() ORIGIN_CITY_IATA = "LON" if sheet_data[0]["iataCode"] == "": for row in sheet_data: row["iataCode"] = flight_search.get_destination_code(row["city"]) data_manager.destination_data = sheet_data data_manager.update_destination_codes() tomorrow = datetime.now() + timedelta(days=1) six_month_from_today = datetime.now() + timedelta(days=(6 * 30)) for destination in sheet_data: flight = flight_search.check_flights( ORIGIN_CITY_IATA, destination["iataCode"], from_time=tomorrow, to_time=six_month_from_today ) if flight.price < destination["lowestPrice"]: notification_manager.telegram_bot_send_text( f"Low price alert! Only £{flight.price} to fly from {flight.origin_city}-{flight.origin_airport} " f"to {flight.destination_city}-{flight.destination_airport}, " f"from {flight.out_date} to {flight.return_date}." )
data_manager.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 import requests SHEETY_PRICES_ENDPOINT = "https://api.sheety.co/*************************/flightDeals/prices/" class DataManager: def __init__(self): self.destination_data = {} def get_destination_data(self): response = requests.get(url=SHEETY_PRICES_ENDPOINT) data = response.json() self.destination_data = data["prices"] return self.destination_data def update_destination_codes(self): for city in self.destination_data: new_data = { "price": { "iataCode": city["iataCode"] } } response = requests.put( url=f"{SHEETY_PRICES_ENDPOINT}/{city['id']}", json=new_data ) print(response.text)
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 import requests from flight_data import FlightData TEQUILA_ENDPOINT = "https://tequila-api.kiwi.com" 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] except IndexError: print(f"No flights found for {destination_city_code}.") return None 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
flight_data.py
1 2 3 4 5 6 7 8 9 10 class FlightData: def __init__(self, price, origin_city, origin_airport, destination_city, destination_airport, out_date, return_date): self.price = price self.origin_city = origin_city self.origin_airport = origin_airport self.destination_city = destination_city self.destination_airport = destination_airport self.out_date = out_date self.return_date = return_date
notification_manager.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import requests BOT_TOKEN = "********************************************" BOT_CHATID = "*********" class NotificationManager: def telegram_bot_send_text(self, bot_message): bot_token = BOT_TOKEN bot_chatID = BOT_CHATID send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message bot_response = requests.get(send_text) return bot_response.json()
代码走读
DataManager.get_destination_data():GET 表格 → 取出 data["prices"] → 存进 self.destination_data 并返回。存一份在实例里 ,后面 update_destination_codes() 直接用。
update_destination_codes():遍历每行,PUT 回写 iataCode。URL 里拼了 city['id']——Sheety 用行 id 定位记录。
FlightSearch.get_destination_code():locations/query 接口,取 results[0]["code"]。只取第一个结果 ,城市名有歧义时(Springfield)会错。
check_flights():一堆参数里几个关键项:
nights_in_dst_from/to:目的地停留 7~28 天;
flight_type: round:往返;
max_stopovers: 0:只要直飞;
curr: GBP:英镑计价。
try: data = response.json()["data"][0] except IndexError: —— 没有航班时不崩溃 ,返回 None。这是本项目里最正确的一处异常处理。
FlightData(...):把接口返回的嵌套字典"拍平"成 7 个属性。data["route"][0] 是去程,[1] 是回程。
main.py:读表 → 补 IATA → 逐个查价 → if flight.price < destination["lowestPrice"] → 发通知。
一个会导致崩溃的 bug
1 2 flight = flight_search.check_flights(...) if flight.price < destination["lowestPrice"]:
check_flights() 在没航班时返回 None,下一行 None.price 直接 AttributeError。正确写法:
1 if flight is not None and flight.price < destination["lowestPrice"]:
try/except 只保护了"取第一个结果",没保护"调用方怎么用返回值"。返回 None 的函数,调用方必须判空 ——这是 Python 里最常见的崩溃来源之一。
其他问题
TEQUILA_API_KEY 硬编码 在 flight_search.py 里,应该走环境变量。
sheet_data[0] 假设表格至少有一行,空表直接 IndexError。
每个目的地都请求一次 :10 个城市就是 10 次请求,免费额度很快就没了。可以一次查"从 LON 出发到所有城市"的最低价。
没有去重 :同一航线每天都发提醒,应该记录"已提醒过的价格"。
运行结果
1 2 Paris: £89 Low price alert! Only £89 to fly from London-LON to Paris-PAR, from 2026-12-03 to 2026-12-10.
易错点
表格里的 lowestPrice 是字符串 :"500" 和数字比较会 TypeError。
IATA 代码大小写 :接口要求大写。
route[1] 不存在 :单程航班没有回程,会 IndexError。
时区/日期格式 :Teqila 要求 %d/%m/%Y(日在前),写成 %Y-%m-%d 会查不到。
动手改
加上 flight is not None 判空。
把密钥改成环境变量。
记录"上次提醒的价格",只有更低时才再提醒。
源文件逐个讲解
6 个文件 ,这是全书第一次「按职责拆成 4 个类」的完整项目:
文件
行数
职责
data_manager.py29 读写 Google Sheet(目的地清单)
flight_search.py57 调 Kiwi/Tequila API:城市→机场码、查机票
flight_data.py11 FlightData:一条航班结果的值对象
notification_manager.py17 发 Telegram
main.py35 组装 + 比价 + 触发提醒
README.md9 说明页
flight_data.py(11 行)——纯数据容器
1 2 3 4 class FlightData: def __init__(self, price, origin_city, origin_airport, destination_city, destination_airport, out_date, return_date): self.price = price ...
七个参数的构造函数 ——这是「参数过多」的信号 。真实项目里会用 @dataclass:
1 2 3 4 5 6 7 from dataclasses import dataclass @dataclass class FlightData: price: int origin_city: str ...
@dataclass 自动生成 __init__、__repr__、__eq__ ,11 行变 8 行。但这份代码用普通类也能跑,只是没有 __repr__,print(flight) 会显示 <flight_data.FlightData object at 0x...> 。
它的作用是「把 API 返回的嵌套字典变成有名字的对象」 :
1 2 3 4 # 用字典 data["route"][0]["cityFrom"] # 用对象 flight.origin_city
后者读起来是人话 ,而且拼错立刻 AttributeError。
data_manager.py(29 行)
1 SHEETY_PRICES_ENDPOINT = "https://api.sheety.co/*************************/flightDeals/prices/"
URL 里的星号是打码的用户 ID ——这份代码原样跑不通,要自己建 Sheety 表。
1 2 3 4 5 def get_destination_data(self): response = requests.get(url=SHEETY_PRICES_ENDPOINT) data = response.json() self.destination_data = data["prices"] return self.destination_data
data["prices"] :Sheety 返回 {"prices": [{...}, {...}]},表名是复数 。
1 2 3 4 5 6 7 8 9 10 11 12 def update_destination_codes(self): for city in self.destination_data: new_data = { "price": { "iataCode": city["iataCode"] } } response = requests.put( url=f"{SHEETY_PRICES_ENDPOINT}/{city['id']}", json=new_data ) print(response.text)
注意两个「单复数」不对称 :
集合端点:.../prices/
单行端点:.../prices/{id}
请求体里的键是单数 "price"
这是 Sheety 的规则 (集合复数、单行单数)。写错就 400。
逐行 PUT :10 个城市就 10 次请求。没有批量接口 ,只能循环。
flight_search.py(57 行)——两个 API
1 2 3 4 5 6 7 8 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
「城市名 → IATA 三字码」 :"Paris" → "PAR"。
results[0] 有风险 :搜不到时 locations 是空列表,[0] 直接 IndexError。没有判空 。
1 2 3 4 5 6 7 8 9 10 11 12 13 def check_flights(self, origin_city_code, destination_city_code, from_time, to_time): 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" }
九个参数,每个都有含义 :
参数
含义
fly_from / fly_to出发/到达机场码
date_from / date_to搜索窗口(格式 dd/mm/yyyy )
nights_in_dst_from / to停留 7–28 天
flight_type: "round"往返
one_for_city: 1每个城市只返回最便宜的一条
max_stopovers: 0只要直飞
curr: "GBP"英镑计价
max_stopovers: 0 是最狠的筛选 ——只要直飞 。好处是价格干净,坏处是很多小城市根本没有直飞,直接返回空。
1 2 3 4 5 try: data = response.json()["data"][0] except IndexError: print(f"No flights found for {destination_city_code}.") return None
这里用 try/except IndexError 处理「没航班」 ——比 if not data 更直接,但只捕获了 IndexError :如果 API 返回错误信息(比如 key 无效),response.json()["data"] 会 KeyError,不会被捕获 。
1 2 3 4 5 6 7 flight_data = FlightData( price=data["price"], origin_city=data["route"][0]["cityFrom"], ... out_date=data["route"][0]["local_departure"].split("T")[0], return_date=data["route"][1]["local_departure"].split("T")[0] )
route[0] 是去程、route[1] 是回程 ——往返票的 route 数组按航段排列。
.split("T")[0] 从 "2026-12-05T08:30:00.000Z" 取日期部分(和 Day 33 的 .split("T")[1] 取时间正好相反)。
route[1] 的风险 :如果只买到单程(flight_type 传错、或 API 只返回一段),route[1] 直接 IndexError。
main.py(35 行)——组装与比价
1 2 3 4 5 6 data_manager = DataManager() sheet_data = data_manager.get_destination_data() flight_search = FlightSearch() notification_manager = NotificationManager() ORIGIN_CITY_IATA = "LON"
LON 是伦敦的城市码 (不是机场码)——Kiwi 支持城市码。
1 2 3 4 5 if sheet_data[0]["iataCode"] == "": for row in sheet_data: row["iataCode"] = flight_search.get_destination_code(row["city"]) data_manager.destination_data = sheet_data data_manager.update_destination_codes()
「只在第一行为空时才批量补码」 ——这是一种「已初始化」的判断 :补过一次之后,表里就有 iataCode 了,不用再查。
风险 :如果第一行有码、后面某行没有,后面那行永远不会被补 。
sheet_data[0] 在空表时 IndexError ——表里一行都没有就崩。
1 2 tomorrow = datetime.now() + timedelta(days=1) six_month_from_today = datetime.now() + timedelta(days=(6 * 30))
timedelta(days=1) 算明天 ,6*30=180 天算半年——用 30 天近似一个月 ,有误差但机票搜索不需要精确。
1 2 3 4 5 6 7 8 for destination in sheet_data: flight = flight_search.check_flights( ORIGIN_CITY_IATA, destination["iataCode"], from_time=tomorrow, to_time=six_month_from_today ) if flight.price < destination["lowestPrice"]:
这里是最严重的 bug :check_flights 可能返回 None (没直飞航班),接着 flight.price 直接 AttributeError: 'NoneType' object has no attribute 'price' 。
整个循环会在第一个「无直飞」的城市崩掉 ,后面的城市都不检查了。
正确写法:
1 2 3 4 5 flight = flight_search.check_flights(...) if flight is None: continue if flight.price < destination["lowestPrice"]: ...
destination["lowestPrice"] 是表里人工填的「心理价位」——比这个低才提醒 。
通知内容拼了 5 个字段 (价格、出发城市-机场、到达城市-机场、去程、回程),信息完整 ,这是好设计。
这份代码的问题
flight.price 没判 None (最严重):第一个无直飞城市就崩。
sheet_data[0] 空表崩 。
「只看第一行有没有 iataCode」 :部分缺失时补不全。
get_destination_code 的 results[0] 没判空 。
route[1] 假设一定有回程 。
update_destination_codes 逐行 PUT,无失败处理 。
所有密钥/URL 都是星号 ,跑不通。
README.md(9 行)
标题 Day 39 - Capstone Part 1: Flight Deal Finder,知识点:OOP、HTTP Requests、API、Sending SMS via the Twilio API、Passing Environment Variables、Using Python to Send SMS。
这一天的重点是「把 Capstone 拆成 4 个类」 ——数据管理、搜索、数据模型、通知,每个类只干一件事 。这是 Day 16 的咖啡机之后,第二次完整的 OOP 项目。
六个文件的关系
1 2 3 4 5 main.py ├── data_manager.DataManager ── Sheety(读/写表) ├── flight_search.FlightSearch ── Tequila(查码/查票) │ └── flight_data.FlightData (结果对象) └── notification_manager.NotificationManager ── Telegram
依赖是单向的 :main 知道所有人,flight_search 只知道 FlightData,FlightData 谁都不认识 。这就是「分层」。