Using kivy Urlrequest

Asked

Viewed 408 times

2

How exactly do you use kivy’s Urlrequest? In this case you would like to download a page that returns a json file. Using the python requests library I can do this easily, but when running the application on android phone, it is minimizing alone, so I need an alternative. This is the code I have using requests:

url = requests.get('pagina_web.json')
page = url.json()
page2 = page['chave1']['chave2']['chave3']['chave4']

I need something similar using Urlrequest or another library, but that works when running the application.

1 answer

1


I think this app explains well how Kivy’s Urlrequest works:

from kivy.network.urlrequest import UrlRequest
from kivy.app import App
from kivy.uix.button import Button



class reqApp(App):
    def build(self):
        bt =  Button(text='Pegar Json do Bitcoin')
        bt.bind(on_press=self.make_request)
        return bt

    def make_request(self, instance):
        UrlRequest('https://www.mercadobitcoin.net/api/BTC/ticker/', self.print_json)

    def print_json(self, req, result):
        print result['ticker']

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

When you click on the button it calls the make_request that makes an instance of UrlRequest. When the object is instantiated it automatically makes an asynchronous request and when it ends (if the request is successful) calls the function print_json.

Remember is asynchronous so the main loop of the GUI will not "lock" until the request is finished, no need to use the python threads.

To have all the details of the parameters that you can pass in Urlrequest see https://kivy.org/docs/api-kivy.network.urlrequest.html

PS: I use the requests library on android in an app I did music and works normal if you want to see: https://github.com/SamuelHaidu/OMAP

If it is very simple you can use the standard python library urllib2

  • has how to save the result of this self.print_json in Urlrequests in a variable?

  • Of course, just put the result into a global variable (the simplest form)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.