Table Of Contents
UrlRequest¶
New in version 1.0.8.
You can use the UrlRequest
to make asynchronous requests on the
web and get the result when the request is completed. The spirit is the
same as the XHR object in Javascript.
The content is also decoded if the Content-Type is application/json and the result automatically passed through json.loads.
The syntax to create a request:
from kivy.network.urlrequest import UrlRequest
req = UrlRequest(url, on_success, on_redirect, on_failure, on_error,
on_progress, req_body, req_headers, chunk_size,
timeout, method, decode, debug, file_path, ca_file,
verify)
Only the first argument is mandatory: the rest are optional.
By default, a “GET” request will be sent. If the UrlRequest.req_body
is
not None, a “POST” request will be sent. It’s up to you to adjust
UrlRequest.req_headers
to suit your requirements and the response
to the request will be accessible as the parameter called “result” on
the callback function of the on_success event.
Example of fetching JSON:
def got_json(req, result):
for key, value in req.resp_headers.items():
print('{}: {}'.format(key, value))
req = UrlRequest('https://httpbin.org/headers', got_json)
Example of Posting data (adapted from httplib example):
import urllib
def bug_posted(req, result):
print('Our bug is posted!')
print(result)
params = urllib.urlencode({'@number': 12524, '@type': 'issue',
'@action': 'show'})
headers = {'Content-type': 'application/x-www-form-urlencoded',
'Accept': 'text/plain'}
req = UrlRequest('bugs.python.org', on_success=bug_posted, req_body=params,
req_headers=headers)
If you want a synchronous request, you can call the wait() method.
- class kivy.network.urlrequest.UrlRequest(url, on_success=None, on_redirect=None, on_failure=None, on_error=None, on_progress=None, req_body=None, req_headers=None, chunk_size=8192, timeout=None, method=None, decode=True, debug=False, file_path=None, ca_file=None, verify=True, proxy_host=None, proxy_port=None, proxy_headers=None, user_agent=None, on_cancel=None, cookies=None)[source]¶
Bases:
threading.Thread
A UrlRequest. See module documentation for usage.
Changed in version 1.5.1: Add debug parameter
Changed in version 1.0.10: Add method parameter
Changed in version 1.8.0: Parameter decode added. Parameter file_path added. Parameter on_redirect added. Parameter on_failure added.
Changed in version 1.9.1: Parameter ca_file added. Parameter verify added.
Changed in version 1.10.0: Parameters proxy_host, proxy_port and proxy_headers added.
Changed in version 1.11.0: Parameters on_cancel added.
- Parameters
- url: str
Complete url string to call.
- on_success: callback(request, result)
Callback function to call when the result has been fetched.
- on_redirect: callback(request, result)
Callback function to call if the server returns a Redirect.
- on_failure: callback(request, result)
Callback function to call if the server returns a Client or Server Error.
- on_error: callback(request, error)
Callback function to call if an error occurs.
- on_progress: callback(request, current_size, total_size)
Callback function that will be called to report progression of the download. total_size might be -1 if no Content-Length has been reported in the http response. This callback will be called after each chunk_size is read.
- on_cancel: callback(request)
Callback function to call if user requested to cancel the download operation via the .cancel() method.
- req_body: str, defaults to None
Data to sent in the request. If it’s not None, a POST will be done instead of a GET.
- req_headers: dict, defaults to None
Custom headers to add to the request.
- chunk_size: int, defaults to 8192
Size of each chunk to read, used only when on_progress callback has been set. If you decrease it too much, a lot of on_progress callbacks will be fired and will slow down your download. If you want to have the maximum download speed, increase the chunk_size or don’t use
on_progress
.- timeout: int, defaults to None
If set, blocking operations will timeout after this many seconds.
- method: str, defaults to ‘GET’ (or ‘POST’ if
body
is specified) The HTTP method to use.
- decode: bool, defaults to True
If False, skip decoding of the response.
- debug: bool, defaults to False
If True, it will use the Logger.debug to print information about url access/progression/errors.
- file_path: str, defaults to None
If set, the result of the UrlRequest will be written to this path instead of in memory.
- ca_file: str, defaults to None
Indicates a SSL CA certificate file path to validate HTTPS certificates against
- verify: bool, defaults to True
If False, disables SSL CA certificate verification
- proxy_host: str, defaults to None
If set, the proxy host to use for this connection.
- proxy_port: int, defaults to None
If set, and proxy_host is also set, the port to use for connecting to the proxy server.
- proxy_headers: dict, defaults to None
If set, and proxy_host is also set, the headers to send to the proxy server in the
CONNECT
request.
- cancel()[source]¶
Cancel the current request. It will be aborted, and the result will not be dispatched. Once cancelled, the callback on_cancel will be called.
New in version 1.11.0.
- property chunk_size¶
Return the size of a chunk, used only in “progress” mode (when on_progress callback is set.)
- decode_result(result, resp)[source]¶
Decode the result fetched from url according to his Content-Type. Currently supports only application/json.
- property error¶
Return the error of the request. This value is not determined until the request is completed.
- get_connection_for_scheme(scheme)[source]¶
Return the Connection class for a particular scheme. This is an internal function that can be expanded to support custom schemes.
Actual supported schemes: http, https.
- property is_finished¶
Return True if the request has finished, whether it’s a success or a failure.
- req_body¶
Request body passed in __init__
- req_headers¶
Request headers passed in __init__
- property resp_headers¶
If the request has been completed, return a dictionary containing the headers of the response. Otherwise, it will return None.
- property resp_status¶
Return the status code of the response if the request is complete, otherwise return None.
- property result¶
Return the result of the request. This value is not determined until the request is finished.
- run()[source]¶
Method representing the thread’s activity.
You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.
- url¶
Url of the request
- wait(delay=0.5)[source]¶
Wait for the request to finish (until
resp_status
is not None)Note
This method is intended to be used in the main thread, and the callback will be dispatched from the same thread from which you’re calling.
New in version 1.1.0.