IntroductionInstallationLimitations of the "file" protocolFrequently asked questionsSyntax, keywords and built-in functionsStandard distributionimport implementationBrython packagesBrowser interface
Introduction - DOM API
Creating a document Accessing elements Attributes, properties and methods Events Mouse events Keyboard events Focus events Drag events Query string Using Javascript objects and libraries Brython-specific built-in modules
browser
browser.aio browser.ajax browser.html browser.local_storage browser.markdown browser.object_storage browser.session_storage browser.svg browser.template browser.timer browser.webcomponent browser.websocket browser.worker Widgets browser.widgets.dialog browser.widgets.menu interpreter javascript Working with BrythonCookbook |
module browser.ajaxThis module allows running Ajax requests. The standard Web API syntax can be used (see below) but Brython proposes a more concise syntax: for each request method (GET, POST, etc.) the module defines a specific function.Methods without a request bodyget( url[, blocking=False, headers={}, mode="text", encoding="utf-8", timeout=None, cache=False, data="", **callbacks])
and the same interface for methods connect, delete, head, options and
trace .
url is the address of the requested resource
blocking is a boolean to specify if the request is blocking or not.
The default value is
headers is a dictionary with the HTTP headers key / values mode is the read mode : "text", "binary", "json", "document" if mode is "text", encoding is the text file encoding
data is either a string, or a dictionary. In the second case, the
dictionary is converted into a string of the form
cache is a boolean to specify if the GET request should use the browser
cache. It is set to
timeout is the time in seconds after which the request is canceled **callbacks is a dictionary where keys are of the form Methods with a request bodypost( url[, blocking=False, headers={"Content-Type":
"application/x-www-form-urlencoded"}, timeout=None, data="", **callbacks])
and the same interface for patch and put .
The parameters have the same meaning as for methods without a request body.
Parameters mode, encoding and cache are not relevant for these methods.
The request body is provided in the argument data. If is is a dictionary,
it is transformed transparently, and the body length (header "Content-Length")
is automatically computed and sent.
Callback functionsCallback functions are called when an event occurs on the Ajax object. Possible events are:
status
HTTP response code (integer) : 200 if the resource was found, 404 if it doesn't exist, etc. text
the response text : instance of json
if request mode is "json", attribute
xml
if request mode is "document", attribute
read()
reads the response in the format determined by request modeThe other event that can be handled is "timeout", triggered if the duration specified in the argument timeout is reached. For this event, the callback
function takes no argument.
ExamplesReading a text filefrom browser import ajax def read(req): print(req.text) ajax.get("test.txt", oncomplete=read)If the text file has an encoding different from UTF-8, the encoding can be specified from browser import ajax def read(req): print(req.text) ajax.get("test-latin1.txt", encoding="latin1", oncomplete=read)Reading a text file as bytes from browser import ajax def read(req): assert isinstance(req.text, bytes) ajax.get("test.txt", mode="binary", oncomplete=read)Reading a binary file (eg an image) from browser import ajax def read(req): assert isinstance(req.read(), bytes) ajax.get("picture.png", mode="binary", oncomplete=read)Reading a file with JSON content from browser import ajax def read(req): print(req.json) ajax.get("test.json", mode="json", oncomplete=read) Standard Web API interfaceAjax requests can also be written with a syntax closer to the standard Web API specification. The module defines the classAjax , called without argument, that returns a
new request object.
A request object has the following methods:
open( method, url, async)
method is the HTTP method used for the request (usually GET or POST), url is the resource location, async is a boolean that indicates whether the call is asynchronous (the script that started the request goes on running without waiting for the response) or not (the script hangs until the response is received). bind( evt, function)
attaches the function to the event evt. The events are the same as above.
The function takes a single argument, the
Once the request is opened, attributes can be specified:
encoding
if the resource specified by the url is a text file,
if the Mime type (cf. documentation)
is not explicitely set, giving a value to
This makes it possible to set the attribute
responseType
the expected rresponse type (cf. documentation) set_header( name, value)
sets the value of the header name. set_timeout( duration, function)
if the query did not return response within duration in seconds, it will cancel the query and execute the function. This function cannot have arguments.All the properties of XMLHTTPRequest objects can be used on the Ajax object. Sending the requestsend( [data])
sends (starts) the request. The optional argument data is ignored if the method is not POST, PUT or PATCH ; it must be a dictionary, or a string representing the url encoding of key-value pairs. If you want to send files, you need to pass a dictionary with one of the keys a File object, e.g. provided you have an input element of type ExampleWe suppose there is a DIV with id result in the HTML pagefrom browser import document, ajax def on_complete(req): if req.status == 200 or req.status == 0: document["result"].html = req.text else: document["result"].html = "error " + req.text req = ajax.Ajax() req.bind('complete', on_complete) # send a POST request to the url req.open('POST', url, True) req.set_header('content-type', 'application/x-www-form-urlencoded') # send data as a dictionary req.send({'x': 0, 'y': 1}) File uploadTo send files entered in a form by a tag such as<input type="file" name="choosefiles" multiple="multiple"> the module provides the function file_upload( url, file, method="POST", field_name="filetosave", [**callbacks])
file is the file object to upload to the url, usually the result of an expression for file in document["choosefiles"].files: ... method is the method used for the upload call, "POST" by default but can be set to "PUT" field_name is the name of the field associated with the file to send. It will be used on the server side to get the dataExample: <script type="text/python"> from browser import ajax, bind, document def upload_ok(req): print("all right") @bind("#upload", "click") def uploadfiles(event): for f in document["choosefiles"].files: ajax.file_upload("/cgi-bin/savefile.py", f, oncomplete=upload_ok) </script> <form> <input id="choosefiles" type="file" multiple="multiple" /> </form> <button id="upload">Upload</button> |