【发布时间】:2021-08-07 22:21:32
【问题描述】:
我正在尝试制作一个简单的程序,它会告诉您今天是否需要给植物浇水(看看今天是否会下雨)。我正在使用 openweathermap api 来做到这一点。 api 不像温度或湿度那样将雨作为变量包含在内,而是仅在下雨作为天气变量的一部分时才显示为“雨”。
当我在下面运行我的代码时,它永远不会知道正在下雨,即使它正在查看的变量包括雨。我想知道如何在变量中找到“rain”一词并相应地打印一条消息。
运行我当前的代码后,如果我打印weathervar,就会得到这样的结果:
[{'id': 502, 'main': 'Rain', 'description': 'heavy intensity rain', 'icon': '10n'}]
即使变量包含“rain”,我的代码也认为它没有。
import requests, json
api_key = "someapikey"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city_name = ("Brunei")
complete_url = base_url + "appid=" + api_key + "&q=" + city_name
response = requests.get(complete_url)
x = response.json()
if x["cod"] != "404":
y = x["main"]
current_temperature = y["temp"]
weathervar = x["weather"]
else:
print(" City Not Found ")
if 'Rain' in weathervar:
print("You don't need to water your plants today.")
else:
print("You need to water your plants today")
print(weathervar)
【问题讨论】:
-
我建议您更改您的帐户信息中的 API 密钥,因为您已经在此处发布了它。这些信息应该是私人的。如果您共享您的 API 密钥,那么知道它的每个人都可以使用您的凭据与 API 进行交互。由于您每次只有一定数量的调用,因此共享此信息不仅不安全,而且其他人可能会自费使用 API。
标签: python openweathermap