T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 33 天:API 与参数:国际空间站过境提醒

这是「Python 100 天」系列第 33 天的学习笔记:API 与参数:国际空间站过境提醒。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

调用两个公开 API:一个告诉你国际空间站(ISS)现在在哪,一个告诉你所在地的日出日落时间。如果 ISS 在头顶 ±5 度范围内、且现在是夜里,就发邮件提醒你抬头看。README 知识点:API 端点与调用、HTTP 状态码与异常、JSON 响应、API 参数。

一、API 是什么

API 就是一个"网址 + 约定":你按格式发请求,它按格式回数据。这里是 HTTP GET:

1
2
3
4
5
import requests

response = requests.get("http://api.open-notify.org/iss-now.json")
response.raise_for_status() # 4xx/5xx 时抛异常
data = response.json() # 把 JSON 文本解析成 dict

requests 是第三方库(pip install requests),比标准库 urllib 好用得多。

二、HTTP 状态码

码 含义
200成功
301/302重定向
401/403未认证 / 无权限
404地址不存在
429请求太频繁(被限流)
500服务器内部错误

raise_for_status() 把"非 2xx"转成异常,不写这一行,404 也会被当成成功,然后 response.json() 解析出一堆 HTML 报错页,报一个莫名其妙的 JSONDecodeError。

三、带参数的请求

1
2
parameters = {"lat": 43.65, "lng": -79.38, "formatted": 0}
response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)

params 会自动拼成 ?lat=43.65&lng=-79.38&formatted=0,还会帮你做 URL 编码(空格变 %20)。永远不要手动拼查询字符串,中文和特殊字符会出错。

formatted=0 让接口返回 ISO 8601 格式(2026-12-02T07:12:33+00:00),而不是"7:12:33 AM",方便程序解析。

代码全文

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
import requests
from datetime import datetime
from time import sleep
import smtplib

MY_EMAIL = "[email protected]"
MY_PASSWORD = "password"
TO_EMAIL = "[email protected]"
MY_LAT = 43.653225
MY_LONG = -79.383186

response = requests.get(url="http://api.open-notify.org/iss-now.json")
response.raise_for_status()
data = response.json()

iss_latitude = float(data["iss_position"]["latitude"])
iss_longitude = float(data["iss_position"]["longitude"])


def within_lat_long():
return MY_LAT-5 <= iss_latitude <= MY_LAT+5 and MY_LONG-5 <= iss_longitude <= MY_LONG+5


parameters = {
"lat": MY_LAT,
"lng": MY_LONG,
"formatted": 0,
}

response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
response.raise_for_status()
data = response.json()
sunrise = int(data["results"]["sunrise"].split("T")[1].split(":")[0])
sunset = int(data["results"]["sunset"].split("T")[1].split(":")[0])
time_now = datetime.now()

while True:
if time_now.hour >= sunset and within_lat_long():
with smtplib.SMTP("smtp.outlook.com") as connection:
connection.starttls()
connection.login(MY_EMAIL, MY_PASSWORD)
connection.sendmail(
from_addr=MY_EMAIL,
to_addrs=TO_EMAIL,
msg="Subject: International Space Station AlertnnLook into the sky, you can see the ISS passing"
)
sleep(60)

代码走读

  1. 第一次请求:拿 ISS 的经纬度,float() 转成数字(JSON 里可能给字符串)。
  2. within_lat_long():判断 ISS 是否在"我的位置 ±5 度"的方形区域内。用方形而不是圆形,是为了不引入三角函数——近似判断在原型阶段完全够用。
  3. 第二次请求:拿日出日落,从 ISO 字符串里切出小时:
1
int(data["results"]["sunrise"].split("T")[1].split(":")[0])

"2026-12-02T07:12:33+00:00" → 按 T 切成两段 → 取第二段 → 按 : 切 → 取第一段 → 得到 "07" → 转 int。

  1. while True: 每 60 秒检查一次。

这段代码的四个问题

(1) time_now 在循环外只取了一次

1
2
3
time_now = datetime.now()
while True:
if time_now.hour >= sunset and within_lat_long():

小时数永远停在启动那一刻,程序跑一整夜也不会更新。应该把 datetime.now() 放进循环里。

(2) 只判断了"晚于日落",没判断"早于日出"

凌晨 3 点也算"夜里",这倒是对的;但 >= sunset 在跨零点时逻辑仍成立(比如 23 点 > 19 点)。真正的问题是:sunset 是 UTC 小时,datetime.now() 是本地时间,两者直接比较是错的。要么统一转 UTC,要么用 astimezone()。

(3) 满足条件就每 60 秒发一封邮件

醒来会发现收件箱有 300 封。应该加一个"已发送"标志,或者用 break。

(4) 没有异常处理

断网、接口超时、返回 429 都会让程序直接崩。真实脚本要 try/except requests.RequestException,失败就等下一轮。

运行结果

ISS 经过你头顶且是夜间时,收到一封 International Space Station Alert 邮件。

易错点

  1. 忘了 raise_for_status():错误被静默吞掉。
  2. response.json() 返回列表:有些接口顶层是数组,不能直接按字典取键。
  3. 经纬度正负号:南纬、西经是负数,写反了会定位到地球另一边。
  4. 免费接口的限流:open-notify 这类公益接口不要高频轮询。

动手改

  • 把 datetime.now() 移进循环,并统一成 UTC 比较。
  • 加"只提醒一次"的标志。
  • 用 try/except 包住请求,失败时打印原因并继续。

源文件逐个讲解

2 个文件:main.py(48 行)、README.md(8 行)。这是全书第一个「调 API」的程序。

main.py(48 行)

结构:两个 API 调用 → 一个判断函数 → 一个死循环

1
2
3
4
5
6
7
8
9
10
import requests
from datetime import datetime
from time import sleep
import smtplib

MY_EMAIL = "[email protected]"
MY_PASSWORD = "password"
TO_EMAIL = "[email protected]"
MY_LAT = 43.653225
MY_LONG = -79.383186

坐标是 43.65 / -79.38 —— 加拿大多伦多。这是作者的所在地(后面 Day 35 的「下雨提醒」用的也是这个坐标)。

(1)第一个 API:ISS 现在在哪

1
2
3
4
5
6
response = requests.get(url="http://api.open-notify.org/iss-now.json")
response.raise_for_status()
data = response.json()

iss_latitude = float(data["iss_position"]["latitude"])
iss_longitude = float(data["iss_position"]["longitude"])

四步是「调 API 的固定套路」:

  1. requests.get(url) 发请求;
  2. raise_for_status():状态码不是 2xx 就抛异常——不写这行,404/500 也会被当成成功;
  3. response.json() 把 JSON 响应体转成字典;
  4. 按下标取字段。

float(...) 是必须的:这个 API 返回的纬度是字符串 "43.6532",不转就没法和数字比较(Python 里 "43" < 45 会 TypeError)。

(2)第二个 API:日出日落

1
2
3
4
5
6
7
8
9
10
11
parameters = {
"lat": MY_LAT,
"lng": MY_LONG,
"formatted": 0,
}

response = requests.get("https://api.sunrise-sunset.org/json", params=parameters)
response.raise_for_status()
data = response.json()
sunrise = int(data["results"]["sunrise"].split("T")[1].split(":")[0])
sunset = int(data["results"]["sunset"].split("T")[1].split(":")[0])

params=parameters 是「查询参数」的标准写法:requests 会拼成 ?lat=...&lng=...&formatted=0,自动处理 URL 编码。手拼字符串容易漏转义。

formatted=0 让时间返回 ISO 8601 格式,长这样:

1
"2024-02-27T12:34:56+00:00"

解析三步:

  1. .split("T")[1] → "12:34:56+00:00"(取 T 后面的时间部分);
  2. .split(":")[0] → "12"(取小时);
  3. int(...) → 12。

只取了小时,分钟和秒全丢了。判断「天黑了没」够用,但要精确提醒就不够。

(3)判断函数

1
2
def within_lat_long():
return MY_LAT-5 <= iss_latitude <= MY_LAT+5 and MY_LONG-5 <= iss_longitude <= MY_LONG+5

Python 支持链式比较:a <= x <= b 等价于 a <= x and x <= b,而且 x 只算一次。

±5 度是「肉眼可见范围」的粗略估计(5 度约 550 公里)。ISS 在 400 公里高空,确实差不多这个范围。

函数用了模块级的 iss_latitude——所以这个值永远是启动时那一次。

(4)死循环

1
2
3
4
5
6
7
8
time_now = datetime.now()

while True:
if time_now.hour >= sunset and within_lat_long():
with smtplib.SMTP("smtp.outlook.com") as connection:
...
msg="Subject: International Space Station AlertnnLook into the sky, you can see the ISS passing"
sleep(60)

这里有三个致命的逻辑错误:

① time_now 在循环外算一次,永远不更新

1
2
3
time_now = datetime.now()      # 只执行一次
while True:
if time_now.hour >= sunset: # 永远用同一个小时

结果是:如果启动时是晚上,就整夜每 60 秒发一封邮件;如果是白天,就永远不发。应该把 datetime.now() 放进循环里。

② iss_latitude/longitude 也只取了一次

ISS 90 分钟绕地球一圈,每小时移动约 4 度。启动时算的那组坐标,几分钟后就完全不对了。应该在循环里重新 requests.get。

③ hour >= sunset 不是「天黑」的完整条件

正确的「天黑」是:

1
time_now.hour >= sunset or time_now.hour <= sunrise

漏了 or hour <= sunrise:凌晨 2 点(hour=2)比 sunset=18 小,判成「不黑」,不发提醒——但那时天确实是黑的。

还有:条件成立时每分钟发一封,没有「发过就停」的标记,收件箱会被刷屏。

这份代码的问题

  1. time_now 不更新(循环外计算)。
  2. ISS 坐标不刷新(只在启动时取一次)。
  3. 天黑判断漏了凌晨(or hour <= sunrise)。
  4. 重复发送无节制:条件成立期间每 60 秒一封。
  5. MY_PASSWORD = "password" 占位符。
  6. 没有异常处理:API 挂了、网络断了,整个程序崩。
  7. sunrise 算了但没用。

README.md(8 行)

标题 Day 33 - API Endpoints & API Parameters - ISS Overhead Notifier,知识点:Using API Calls and Working with JSON Data、Understanding API Parameters and How to Use them、Sending Emails with smtplib。

三条正好对应三段:ISS 那个 API(JSON)、日出日落那个 API(参数)、发邮件。

文件间关系

单文件,依赖 requests(第三方,需 pip install requests)、smtplib(标准库)、datetime。

两个 API 的分工:一个回答「ISS 在哪」,一个回答「现在天黑吗」——两个条件同时成立才提醒。这种「多个数据源组合判断」是 Day 36 股票新闻提醒的雏形。

微信收款码 微信
支付宝收款码 支付宝
评论