Kivy – UrlRequest


Kivy – UrlRequest



”;


The UrlRequest class in Kivy framework lets you make asynchronous requests on the web and get the result when the request is completed. Its functionality is same as the XHR object in JavaScript.

The UrlRequest class is defined in the “kivy.network.urlrequest” module. The constructor needs only one mandatory argument named as “url”. The class inherits Thread class in Python”s threading module.

The parameters of UrlRequest constructor are −

  • url − string representing the complete url string to call.

  • on_success − A Callback function to call when the result has been fetched.

  • on_redirect − A Callback function to call if the server returns a Redirect.

  • on_failure − A Callback function to call if the server returns a Client or Server Error.

  • on_error − A Callback function to call if an error occurs.

  • on_progress − A Callback function that will be called to report progression of the download.

  • on_cancel − A Callback function to call if user requested to cancel the download operation via the .cancel() method.

  • on_finish − An additional callback function to call if request is done.

  • req_body − string representing data to be sent along with the request. If this parameter is included, a POST will be done. If not, GET request is sent.

  • req_headers − dict, defaults to None Custom headers to add to the request.

  • chunk_size − Size of each chunk to read, used only when on_progress callback has been set.

  • timeout − An integer, if set, blocking operations will timeout after this many seconds.

  • method − The HTTP method to use, defaults to ”GET” (or ”POST” if body is specified)

  • decode − bool, defaults to True. If False, skip decoding of the response.

  • debug − bool, defaults to False.

  • auth − HTTPBasicAuth, defaults to None. If set, request will use basicauth to authenticate.

The cancel() method of UrlRequest object cancels the current request and the callback on_cancel will be called.

Example

First, we design a user interface consisting of a spinner holding URLs of httpbin.org with variable parameters, two readonly textboxes – one displays the result of URL fetched and second, the JSON string of the response headers. In between, an Image widget is placed. It displays an image if the content_type is of image type. These widgets are placed ina vertical bo layout.

The layout is built with the following kv language script.


#:import json json

BoxLayout:
   orientation: ''vertical''
   TextInput:
      id: ti
      hint_text: ''type url or select from dropdown''
      size_hint_y: None
      height: 48
      multiline: False
   BoxLayout:
      size_hint_y: None
      height: 48
      Spinner:
         id: spinner
         text: ''select''
         values:
            [
               ''http://httpbin.org/ip'',
               ''http://httpbin.org/headers'',
               ''http://httpbin.org/delay/3'',
               ''https://httpbin.org/image/png'',
            ]
         on_text: ti.text = self.text
      Button:
         text: ''GET''
         on_press: app.fetch_content(ti.text)
         size_hint_x: None
         width: 50
   TextInput:
      readonly: True
      text: app.result_text
   Image:
      source: app.result_image
      nocache: True
   TextInput
      readonly: True
      text: json.dumps(app.headers, indent=2)

The Kivy App class code is as given below. It basically sends different HTTP requests to httpbin.org. httpbin.org is a simple HTTP Request & Response Service. The application stores the result of UrlRequest in three string variables and displays in the widgets.

When a URL is selected from the dropdown and the GET button is pressed, it invokes the fetch_content() method and collects the responses.

If the repose header contains a content_type with image, the Image widget loads the image.


from kivy.lang import Builder
from kivy.app import App
from kivy.network.urlrequest import UrlRequest
from kivy.properties import NumericProperty, StringProperty, DictProperty
import json
from kivy.core.window import Window

Window.size = (720,400)

class UrlExample(App):
   status = NumericProperty()
   result_text = StringProperty()
   result_image = StringProperty()
   headers = DictProperty()

   def build(self):
      pass

   def fetch_content(self, url):
      self.cleanup()
      UrlRequest(
         url,
         on_success=self.on_success,
         on_failure=self.on_failure,
         on_error=self.on_error
      )
   
   def cleanup(self):
      self.result_text = ''''
      self.result_image = ''''
      self.status = 0
      self.headers = {}
   
   def on_success(self, req, result):
      self.cleanup()
      headers = req.resp_headers
      content_type = headers.get(''content-type'', headers.get(''Content-Type''))
      if content_type.startswith(''image/''):
         fn = ''tmpfile.{}''.format(content_type.split(''/'')[1])
         with open(fn, ''wb'') as f:
            f.write(result)
         self.result_image = fn
      else:
         if isinstance(result, dict):
            self.result_text = json.dumps(result, indent=2)
         else:
            self.result_text = result
            self.status = req.resp_status
            self.headers = headers
   
   def on_failure(self, req, result):
      self.cleanup()
      self.result_text = result
      self.status = req.resp_status
      self.headers = req.resp_headers
   
   def on_error(self, req, result):
      self.cleanup()
      self.result_text = str(result)
      
UrlExample().run()

Output

Run the above code. Select the ”http://httpbin.org/headers” from the spinner dropdown and press the GET button. You should see the response header in the text boxes.


Kivy UrlRequest

Choose ”https://httpbin.org/image/png” URL. The image will be displayed as shown.


Kivy UrlRequest Image

One of the options in the spinner dropdown is a URL pointing to the IPaddress of the client. Select ”http://httpbin.org/ip” from the list. The IP address will be displayed as shown below −


kivy ip address

Advertisements

”;

Leave a Reply

Your email address will not be published. Required fields are marked *