Introduction

Installation

Limitations of the "file" protocol

Frequently asked questions

Syntax, keywords and built-in functions

Standard distribution

import implementation

Brython packages

Browser interface

Introduction - DOM API
Creating a document
Accessing elements
Attributes, properties and methods

Events
Mouse events
Keyboard events
Focus events
Drag events

Query string

Interactions with Javascript

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 Brython

Execution options
Testing and debugging
Deploying an application

Cookbook

Hello world !
Insert content in an element
HTML markup (bold,italic...)
HTML table
Bind and unbind events
Handle options in a SELECT
Drag and drop
Get the content of an element
Read the content of a file
Store objects locally
Example of onmouseover
 

module browser.ajax

This module manages 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 body

get(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 False (asynchronous request)

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, a dictionary, or an object created by form_data()(see below). In the second case, the dictionary is converted into a string of the form x=1&y=2.

cache is a boolean to specify if the GET request should use the browser cache. It is set to False by default, which means that a random numeric parameter is added to the request

timeout is the time in seconds after which the request is canceled

**callbacks is a dictionary where keys are of the form on + event name (onloaded, oncomplete...) and the value is the callback function that handles this event

Methods with a request body

post(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 functions

Callback functions are called when an event occurs on the Ajax object.

Possible events are:

  • "uninitialized" : not initialized
  • "loading" : established connection
  • "loaded": received request
  • "interactive": response in progress
  • "complete" : finished

Generally, only the function for the event "complete" is defined.

Callback functions take a single argument, the Ajax object. In the function body, the following attributes and methods of this object can be used:

status

HTTP response code (integer) : 200 if the resource was found, 404 if it doesn't exist, etc.

text

the response text : instance of str if request mode is "text", "json" or "xml", instance of bytes if mode is "binary"

json

if request mode is "json", attribute json is the object obtained by parsing the JSON string sent by the server

xml

if request mode is "document", attribute xml is the object containing the XML tree obtained from the response string

read()

reads the response in the format determined by request mode

The 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.

Examples

Reading a text file

from 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 interface

Ajax requests can also be written with a syntax closer to the standard Web API specification.

The module defines the class Ajax, 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 Ajax instance, with the same attributes as above.

Once the request is opened, attributes can be specified:

encoding
if the resource specified by the url is a text file, encoding is the file encoding

if the Mime type (cf. documentation) is not explicitely set, giving a value to encoding sets the Mime type to "text/plain;charset=x-user-defined".

This makes it possible to set the attribute text to the file content with the specified encoding

responseType
the expected response type (cf. documentation)

withCredentials
whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates (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.

Form data

The data sent in a request is a set of key-value pairs. Besides a string or a dictionary, a key-value pair structure can be created by

form_data([form])

If form is passed, it must be an HTML FORM element; in this case the keys and values are built from the form content.

The interface is decribed in the Web API specification. The most common method is

form_data.append(name, value[, filename])

Sending the request

send([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, a string or an object created by form_data()

Example

We suppose there is a DIV with id result in the HTML page

from 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 upload

To send files entered in a form by a tag such as

<input type="file" name="choosefiles" multiple="multiple">

you can use the general methods described above

<input type="file" id="file_upload">
<button id="btn">send</button>

<script type="text/python">
from browser import document, bind, ajax

def complete(ev):
  print('req complete', ev.text)

@bind('#btn', 'click')
def send(ev):
  print(document['file_upload'].files[0])
  req = ajax.Ajax()
  form_data = ajax.form_data()
  form_data.append("upload", document['file_upload'].files[0])
  req.open('POST', '/cgi-bin/file_upload.py')
  req.bind('complete', complete)
  req.send(form_data)

</script>

For a more straightforward version, the module provides the function

file_upload(url, file, method="POST", field_name="filetosave", [headers, timeout, data, **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 data

headers and timeout have the same meaning as above

additional data can be added to the request; it must be a dictionary or an object created by form_data()

Example:

<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>