这是「Python 100 天」系列第 40 天的学习笔记:Capstone(二):Flight Club 多人订阅 。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。
今天要解决的问题
在 Day 39 的基础上做三件事:支持多个订阅用户 (表格里多一张 users 表)、支持一次中转 的航班、把提醒从 Telegram 改成群发邮件 。README 知识点:OOP、HTTP、SMTP 发信、strftime。
一、从"一个人"到"一群人"
1 2 3 users = data_manager.get_customer_emails() emails = [row["email"] for row in users] names = [row["firstName"] for row in users]
列表推导式把"用户记录列表"抽成两个平行列表。这里 names 其实没被用到(代码里只有 emails 参与发送),属于冗余。
二、降级策略:先查直飞,没有再查中转
1 2 3 4 5 6 try: data = response.json()["data"][0] except IndexError: query["max_stopovers"] = 1 # 放宽条件重查 response = requests.get(...) data = response.json()["data"][0]
这是一个很实用的模式:先按最严格要求查,查不到就放宽条件 。注意中转时 route 的下标全变了:
直飞往返:route[0] 去程、route[1] 回程;
一次中转往返:route[0] 去程第一段、route[1] 去程第二段、route[2] 回程第一段。
所以中转分支里 destination_city = data["route"][1]["cityTo"]、return_date = data["route"][2]...。下标依赖数据结构,是这段代码最脆弱的地方。
三、群发邮件
1 2 3 4 5 6 with smtplib.SMTP(...) as connection: connection.starttls() connection.login(...) for email in emails: connection.sendmail(from_addr=..., to_addrs=email, msg=f"Subject:...nn{message}".encode("utf-8"))
一次连接、多次发送 :不要在循环里重复登录;
.encode("utf-8") :邮件正文含 £ 等非 ASCII 字符时必须编码;
收件人用 to_addrs=email(字符串),多个收件人也可以传列表,但会互相看到邮箱,群发要用 BCC 。
代码全文
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 from datetime import datetime, timedelta from data_manager import DataManager from flight_search import FlightSearch from notification_manager import NotificationManager ORIGIN_CITY_IATA = "LON" data_manager = DataManager() flight_search = FlightSearch() notification_manager = NotificationManager() sheet_data = data_manager.get_destination_data() if sheet_data[0]["iataCode"] == "": city_names = [row["city"] for row in sheet_data] data_manager.city_codes = flight_search.get_destination_codes(city_names) data_manager.update_destination_codes() sheet_data = data_manager.get_destination_data() destinations = { data["iataCode"]: { "id": data["id"], "city": data["city"], "price": data["lowestPrice"] } for data in sheet_data} tomorrow = datetime.now() + timedelta(days=1) six_month_from_today = datetime.now() + timedelta(days=6 * 30) for destination_code in destinations: flight = flight_search.check_flights( ORIGIN_CITY_IATA, destination_code, from_time=tomorrow, to_time=six_month_from_today ) print(flight.price) if flight is None: continue if flight.price < destinations[destination_code]["price"]: users = data_manager.get_customer_emails() emails = [row["email"] for row in users] names = [row["firstName"] for row in users] message = f"Low price alert! Only £{flight.price} to fly from {flight.origin_city}-{flight.origin_airport} to {flight.destination_city}-{flight.destination_airport}, from {flight.out_date} to {flight.return_date}." if flight.stop_overs > 0: message += f"nFlight has {flight.stop_overs} stop over, via {flight.via_city}." link = f"https://www.google.co.uk/flights?hl=en#flt={flight.origin_airport}.{flight.destination_airport}.{flight.out_date}*{flight.destination_airport}.{flight.origin_airport}.{flight.return_date}" notification_manager.send_emails(emails, message, link)
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 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: 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
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 29 30 31 32 33 34 35 36 import requests SHEETY_PRICES_ENDPOINT = "https://api.sheety.co/********************************/flightDeals/prices/" SHEETY_USERS_ENDPOINT = "https://api.sheety.co/*********************************/flightDeals/users" 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) def get_customer_emails(self): customers_endpoint = SHEETY_USERS_ENDPOINT response = requests.get(url=customers_endpoint) data = response.json() self.customer_data = data["users"] return self.customer_data
flight_data.py
1 2 3 4 5 6 7 8 9 10 11 12 13 class FlightData: def __init__( self, price, origin_city, origin_airport, destination_city, destination_airport, out_date, return_date, stop_overs=0, via_city=""): 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 self.stop_overs = stop_overs self.via_city = via_city
notification_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 29 30 import smtplib import requests BOT_TOKEN = "******************************************" BOT_CHATID = "*********" MAIL_PROVIDER_SMTP_ADDRESS = "smtp.outlook.com" MY_EMAIL = "***********************" MY_PASSWORD = "p*********" 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() def send_emails(self, emails, message, google_flight_link): with smtplib.SMTP(MAIL_PROVIDER_SMTP_ADDRESS) as connection: connection.starttls() connection.login(MY_EMAIL, MY_PASSWORD) for email in emails: connection.sendmail( from_addr=MY_EMAIL, to_addrs=email, msg=f"Subject:New Low Price Flight!nn{message}n{google_flight_link}".encode('utf-8') )
代码走读
if sheet_data[0]["iataCode"] == "": 只在首次运行时补全机场代码,补完重新拉一次表格。
destinations = {iataCode: {...} for data in sheet_data}:用字典推导式建索引 ,把"列表查找"变成"哈希查找",后面按代码取价格是 O(1)。
逐个查价 → 拼消息 → 有中转就追加一句 → 拼 Google Flights 链接 → 群发。
FlightData 新增 stop_overs、via_city 两个带默认值 的参数,直飞时不用传。
两个会直接崩的 bug
(1) 先取属性再判空
1 2 3 4 flight = flight_search.check_flights(...) print(flight.price) # ← flight 可能是 None if flight is None: continue
没航班时 print(flight.price) 立刻 AttributeError。判空必须放在任何属性访问之前。
(2) 方法名不一致
1 data_manager.city_codes = flight_search.get_destination_codes(city_names)
FlightSearch 里只有 get_destination_code(单数,一次查一个),这里调的是复数版本——AttributeError: 'FlightSearch' object has no attribute 'get_destination_codes'。这是重构后忘了同步调用方 的典型。
运行结果
订阅者每人收到一封:
1 2 3 4 5 Subject: New Low Price Flight! Low price alert! Only £89 to fly from London-LON to Paris-PAR, from 2026-12-03 to 2026-12-10. Flight has 1 stop over, via Amsterdam. https://www.google.co.uk/flights?hl=en#flt=...
易错点
route 下标 :中转和直飞的结构不同,混用必错。
邮件被拒 :免费邮箱 SMTP 有每日发送上限,且大量群发容易被判垃圾。
sheet_data[0] :空表直接 IndexError。
价格类型 :表格读出来是字符串,比较前要 int()/float()。
动手改
把 print(flight.price) 移到判空之后。
补一个 get_destination_codes(city_names) 批量查询方法。
用 BCC 群发,保护订阅者隐私。
源文件逐个讲解
6 个文件 ,Day 39 的升级版:加了「用户订阅」和中转航班兜底。
文件
行数
职责
data_manager.py37 读写两个 Sheet(价格表 + 用户表)
flight_search.py62 查机票,直飞没有就查一次中转
flight_data.py14 值对象,加了 stop_overs / via_city
notification_manager.py26 Telegram + 群发邮件
main.py54 组装 + 比价 + 拼链接
README.md9 说明页
data_manager.py(37 行)——两个端点
1 2 SHEETY_PRICES_ENDPOINT = "https://api.sheety.co/****/flightDeals/prices/" SHEETY_USERS_ENDPOINT = "https://api.sheety.co/****/flightDeals/users"
价格表末尾有斜杠、用户表末尾没有 ——prices/ 后面还要接 /{id},users 不用。这种细节不一致很容易 404 。
1 2 3 4 5 6 def get_customer_emails(self): customers_endpoint = SHEETY_USERS_ENDPOINT response = requests.get(url=customers_endpoint) data = response.json() self.customer_data = data["users"] return self.customer_data
data["users"] :表名叫 users,返回的键也是 users(对比价格表的 prices)。
customers_endpoint = SHEETY_USERS_ENDPOINT 是多此一举的别名 ——直接用常量就行。
flight_data.py(14 行)——加了两个可选参数
1 2 def __init__( self, price, origin_city, origin_airport, destination_city, destination_airport, out_date, return_date, stop_overs=0, via_city=""):
stop_overs=0、via_city="" 有默认值 ——直飞时不用传,中转时才传。这是「给新字段加默认值,不破坏旧调用」的标准做法 。
flight_search.py(62 行)——try/else 的少见用法
1 2 3 4 5 6 7 8 9 10 11 12 try: data = response.json()["data"][0] except IndexError: query["max_stopovers"] = 1 response = requests.get(...) # 再查一次,允许 1 次中转 data = response.json()["data"][0] pprint(data) # ← NameError flight_data = FlightData(..., stop_overs=1, via_city=data["route"][0]["cityTo"]) return flight_data else: flight_data = FlightData(...) # 直飞 return flight_data
核心思路 :先只要直飞(max_stopovers: 0),查不到就把参数改成 1 再查一次 。这是「降级重试」。
pprint(data) 是个真 bug :文件里没有 import pprint 。只要走到中转分支,立刻 NameError: name 'pprint' is not defined。说明这个分支作者没真跑通过 (或者跑通时删了 import)。
中转分支的下标是 route[1] 和 route[2] :
1 2 destination_city=data["route"][1]["cityTo"], return_date=data["route"][2]["local_departure"].split("T")[0],
因为中转票有四段航程 :去程1(出发→中转)、去程2(中转→目的)、回程1、回程2。所以「到达城市」在 route[1],「回程出发」在 route[2]。
via_city=data["route"][0]["cityTo"] :第一段的终点就是中转城市。
第二次查也可能 IndexError :允许 1 次中转还查不到,response.json()["data"][0] 会抛异常,这次没有 try 包着 ,直接崩。
notification_manager.py(26 行)
1 2 3 4 5 6 7 8 9 10 def send_emails(self, emails, message, google_flight_link): with smtplib.SMTP(MAIL_PROVIDER_SMTP_ADDRESS) as connection: connection.starttls() connection.login(MY_EMAIL, MY_PASSWORD) for email in emails: connection.sendmail( from_addr=MY_EMAIL, to_addrs=email, msg=f"Subject:New Low Price Flight!nn{message}n{google_flight_link}".encode('utf-8') )
「一次连接、多封发送」 :SMTP 连接和登录在循环外,只在循环里 sendmail 。这比每封信都重连高效得多(Day 32 是单封,没这个问题)。
.encode('utf-8') :邮件正文里有 £ 符号,必须编码成字节 ,否则 UnicodeEncodeError。
msg=f"Subject:New Low Price Flight!nn..." :Subject: 后面没有空格 ——有些邮件客户端会把「New」当成标题的一部分,显示成 New Low Price Flight!(还算正常),但规范写法是 Subject: New...。
main.py(54 行)
1 2 3 4 5 if sheet_data[0]["iataCode"] == "": city_names = [row["city"] for row in sheet_data] data_manager.city_codes = flight_search.get_destination_codes(city_names) data_manager.update_destination_codes() sheet_data = data_manager.get_destination_data()
这里调了 flight_search.get_destination_codes(city_names)(复数) ——但 flight_search.py 里只有 get_destination_code(单数) 。
这是本书最典型的「调用了不存在的方法」 :AttributeError: 'FlightSearch' object has no attribute 'get_destination_codes'。而且它只在「表里 iataCode 为空」时才触发 ,如果表已经填好了,这段永远不执行,看起来一切正常 。
这是 Day 39 → Day 40 重构留下的半成品 :Day 39 是逐行调单数版,Day 40 想改成批量,但 flight_search.py 没跟着改。
1 2 3 4 5 6 destinations = { data["iataCode"]: { "id": data["id"], "city": data["city"], "price": data["lowestPrice"] } for data in sheet_data}
字典推导式建索引 :以 iataCode 为键,后面 destinations[destination_code]["price"] 直接查 。
这比 Day 39 的「遍历列表 + 每行取字段」更清晰 ,也更适合「按码查询」。
1 2 3 4 5 for destination_code in destinations: flight = flight_search.check_flights(...) print(flight.price) if flight is None: continue
print(flight.price) 写在 if flight is None 之前——这是最直接的 bug :
check_flights 理论上可能返回 None,
但 None.price 先执行,AttributeError 。
if flight is None: continue 本身是对的 (Day 39 缺这个),但位置放错了 。应该是:
1 2 3 4 flight = flight_search.check_flights(...) if flight is None: continue print(flight.price)
这个 bug 很典型 :print 是调试时加的,加完忘了挪到判空之后。
1 2 3 4 5 6 7 8 9 10 11 12 13 if flight.price < destinations[destination_code]["price"]: users = data_manager.get_customer_emails() emails = [row["email"] for row in users] names = [row["firstName"] for row in users] message = f"Low price alert! Only £{flight.price} to fly from ..." if flight.stop_overs > 0: message += f"nFlight has {flight.stop_overs} stop over, via {flight.via_city}." link = f"https://www.google.co.uk/flights?hl=en#flt={flight.origin_airport}.{flight.destination_airport}.{flight.out_date}*{flight.destination_airport}.{flight.origin_airport}.{flight.return_date}" notification_manager.send_emails(emails, message, link)
四个要点 :
get_customer_emails() 在循环里调 :每个「有特价」的城市都重新拉一次用户表——应该在外面拉一次 。
names 取了但没用 :死代码(本来想「Dear {name}」)。
中转信息追加到 message :这是 Day 39 没有的。
Google Flights 的深链 :#flt=出发.到达.日期*到达.出发.日期——用 * 分隔去程和回程 ,这是 Google Flights 的 URL 约定。
这份代码的问题
print(flight.price) 在判空之前 (最严重)。
get_destination_codes(复数)不存在 (第二个严重 bug,且只在特定条件下触发)。
pprint 没 import 。
get_customer_emails 在循环里重复调用 。
names 死代码 。
中转分支的第二次查询没有异常保护 。
所有密钥都是星号 。
README.md(9 行)
标题 Day 40 - Capstone Part 2: Flight Club,知识点:OOP、HTTP Requests、API、Sending SMS via the Twilio API、Passing Environment Variables、Using Python to Send SMS、Email sending with smtplib。
「Flight Club」= 多人订阅 ——所以这一天加了 users 表和 send_emails 群发。
六个文件的关系
1 2 3 4 5 main.py ├── data_manager.DataManager ── 两个 Sheet ├── flight_search.FlightSearch ── Tequila(直飞 → 中转降级) │ └── flight_data.FlightData(多了中转字段) └── notification_manager.NotificationManager ── Telegram + 邮件群发
和 Day 39 只差三处 :多一个 users 端点、check_flights 加了降级重试、通知从 Telegram 扩到邮件。其余代码几乎逐字相同 ——这就是「Capstone 分两天做」的意思:第一天跑通,第二天加功能。