【问题标题】:Python / Kivy - UrlRequest resultsPython / Kivy - UrlRequest 结果
【发布时间】: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 通常在使用外部库方面没有问题。

标签: python kivy


【解决方案1】:

这里的问题是你在下载成功之前打印了结果。

还记得在链接字符串前面加上“http://”。

请记住,网址是异步加载的。 正如UrlRequest 上的文档中所说的那样

您可以使用 UrlRequest 在 Web 上进行异步请求,并在请求完成时获取结果。精神与Javascript中的XHR对象相同。

这就是为什么要在 UrlRequest 中使用 on_success 参数的原因

我给你举个例子。

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 MyWidget(BoxLayout):
    def __init__(self,**kwargs):
        super(MyWidget,self).__init__(**kwargs)
        search_url = "http://api.openweathermap.org/data/2.5/forecast/daily?APPID=ef4f6b76310abad083b96a45a6f547be&q=new%20york"
        print search_url
        self.request = UrlRequest(search_url, self.res)
        print self.request
        print "Result: before success", self.request.result,"\n"


    def res(self,*args):
        print "Result: after success", self.request.result


class MyApp(App):
    def build(self):
        return MyWidget()


if __name__ == '__main__':
    MyApp().run()

【讨论】:

  • 好的,我明白了。这是正确的。但无论如何, urlrequest 永远不会调用 found_location 方法。这是为什么? Tks
  • @MarceloBoy 它基本上是我的 res 函数。尝试将 *args 作为最后一个参数。
  • 你好,谢谢你的帮助。我得到了,真的是菜鸟的错误。在 url 中缺少“http://”,但这就是书中的方式。无论如何,非常感谢。
  • @MarceloBoy 啊忘了在我的回答中提到这一点。但是我在写的时候很认真。我将更新答案以供将来参考。泰
【解决方案2】:

#Ok Guys 这是重磅炸弹

从 kivy.network.urlrequest 导入 UrlRequest 从 kivy.clock 导入时钟 类控制器(对象):

def asynchronous_api_request(self, url):
    '''
    Method asynchronous_api_request is coded using Kivy urlrequest.py.
    '''
    Clock.start_clock()         # Start the Kivy clock
    req = UrlRequest(url)       # get request thread
    while not req.is_finished:  # start while loop to test is_finished
        Clock.tick()            # tick clock per cycle
    Clock.stop_clock()          # Stop the clock
    return req.result           # Return the results

如果 name == 'ma​​in':

ctl = Controller()
data = ctl.asynchronous_api_request('https://www.google.com')
print(data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多