我目前正在阅读 O'Reilly 的 Creating Apps in Kivy 并且有一个例子我无法正常工作,因为当时他写了这本书 openWeatherMap不需要 API key (APPID),但现在需要。我是一名新手程序员,不知道如何更改代码才能正常工作。
这是 main.py 的源代码:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
import json
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
def search_location(self):
search_template = "http://api.openweathermap.org/data/2.5" + "find?q={}&type=like"
search_url = search_template.format(self.search_input.text)
request = UrlRequest(search_url, self.found_location)
def found_location(self, request, data):
data = json.loads(data.decode()) if not isinstance(data, dict) else data
cities = ["{} ({})".format(d['name'], d['sys']['country'])
for d in data['list']]
self.search_results.item_strings = cities
print("\n".join(cities))
class WeatherApp(App):
pass
if __name__ == '__main__':
WeatherApp().run()
这是 weather.kv 源代码:
AddLocationForm:
<AddLocationForm>:
orientation: "vertical"
search_input: search_box
search_results: search_results_list
BoxLayout:
height: "40dp"
size_hint_y: None
TextInput:
id: search_box
size_hint_x: 50
Button:
text: "Search"
size_hint_x: 25
on_press: root.search_location()
Button:
text: "Current Location"
size_hint_x: 25
ListView:
id: search_results_list
item_strings: []
代码很简单。您在文本框中输入城市名称并点击搜索,它会通过显示收到的名称来确认。
请您参考如下方法:
好的,所以我不知道我是否迟到了但是最近买了这本书,我也发现自己正好陷入了这个问题。在谷歌搜索这个问题时,我偶然发现了您的问题以及本书的 O'Reilly 链接。对于这个问题,作者是这样说的:
"I've confirmed the issue; openweathermap has changed their query process and the urls in the book are now all broken. This is going to utterly ruin the reader experience for all new readers; we'll need to do an update and should maybe talk about a second edition."
幸运的是,一位好心人找到了解决这个问题的方法。但为此,您必须先创建一个免费的 Open Weather 帐户。创建帐户后,您将获得一个 API key 。它会在您的个人资料中。
所以,现在这段代码:
search_template = "http://api.openweathermap.org/data/2.5" + "find?q={}&type=like"
变成:
search_template = "http://api.openweathermap.org/data/2.5/find?q={}&type=like&APPID=" + "YOUR_API_KEY"
这对我有用。我知道我迟到了 3 个月,到现在你可能已经得到了答案,但我认为这对遇到类似问题的人很有用,他们的谷歌结果会将他们带到这个地方。
