【发布时间】:2016-07-20 03:29:11
【问题描述】:
我已经为此苦苦挣扎了一段时间,但找不到解决方案。
所以我在 Dusty Phillips 的“Creating Apps in Kivy”中学习 Python 和 Kivy。 这是一个简单的天气应用程序,当我尝试从 openweathermap.com 获取数据时,UrlRequest 函数无法正常工作。我对 kivy 和 python 等很陌生,但正如我所见,该函数必须使用两个参数调用“found_location”方法:请求和结果(从 url 获得的列表)。 如果我从浏览器访问 url,我会得到正确的结果,但回到 python,“结果”为 NONE。
这是带有一些用于调试的打印的代码:
from kivy.app import App
#kivy.require("1.9.1")
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.network.urlrequest import UrlRequest
class AddLocationForm(BoxLayout):
search_input = ObjectProperty()
search_results = ObjectProperty()
def search_location(self):
search_template = "api.openweathermap.org/data/2.5/forecast/daily?APPID=ef4f6b76310abad083b96a45a6f547be&q=" + "{}"
search_url = search_template.format(self.search_input.text)
print search_url
request = UrlRequest(search_url, self.found_location)
print request
print "Result: ", request.result
def found_location(self, request, data):
print request
print 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']]
print cities
self.search_results.item_strings = cities
print "DONE"
class WeatherApp(App):
pass
if __name__ == '__main__':
WeatherApp().run()
这里是控制台:
[INFO ] [OSC ] using <multiprocessing> for socket
[INFO ] [Base ] Start application main loop
[INFO ] [GL ] NPOT texture support is available
api.openweathermap.org/data/2.5/forecast/daily?APPID=ef4f6b76310abad083b96a45a6f547be&q=London
<UrlRequest(Thread-1, started daemon 139654193755904)>
Result: None
如您所见,它传递了正确的 URL,在浏览器中我得到了正确的结果,但从未调用过“found_location”方法,并且在 python 中 request.results = None
我做错了什么?
希望你们能理解我的问题。感谢您的帮助,对不起英语。
【问题讨论】:
-
不是一个真正的答案,但您是否尝试过使用请求库 (docs.python-requests.org/en/master)?这是处理 HTTP 的事实上的标准 Python 方式,并且 kivy 通常在使用外部库方面没有问题。