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

Mouse events
Keyboard events
Focus events
Drag events

Query string

Using Javascript objects and libraries

Brython-specific built-in modules




Working with Brython

Options of function brython()
Testing and debugging
Deploying an application


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 allows running Ajax requests. It defines a single class :

returns an ajax object

This object has the following attributes and methods :

bind(evt, function)
attaches the function to the event evt. evt is a string that matches the different request states :

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

The function takes a single argument, the Ajax instance.

open(method, url, async)
method is the HTTP method used for the request (usually GET or POST),

url is the url to call,

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

an integer representing the request state (cf table below).

readyState request state

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.

sends (starts) the request. The optional argument data is ignored if the method is not POST ; 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 file and id upload_file you could send the user selected file under the key upload by calling send({'upload':doc["upload_file"].elt.files[0]})

an integer representing the HTTP status of the request. The most usual are 200 (ok) and 404 (file not found).

the server response as a string of characters.

the server response as a DOM object.


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
       document["result"].html = "error " + req.text

req = ajax.Ajax()
req.bind('complete', on_complete)
# send a POST request to the url'POST', url, True)
req.set_header('content-type', 'application/x-www-form-urlencoded')
# send data as a dictionary
req.send({'x': 0, 'y': 1})


GET and POST calls can be performed in a more straightforward way with the matching functions:

get(url[, blocking=False, headers={}, mode="text", encoding="utf-8", timeout=None, cache=False, data="", **callbacks])

and the same for delete, head and options.

post(url[, blocking=False, headers={"Content-Type": "application/x-www-form-urlencoded"}, timeout=None, data="", **callbacks])

and the same for put.

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 "text" or "binary"

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 x=1&y=2.

cache is a boolean to specify if the GET request should use the browser cache

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 function that handles this event. For the key ontimeout, the value is the function to call if the duration defined in timeout has been reached.

In the callback function, the Ajax object has a method read() that reads the response content as a string if mode is "text" and as bytes if mode is "binary".

The above example can be written with this shortcut:

from browser import document, ajax

def on_complete(req):
    if req.status == 200:
        document["result"].html = req.text
        document["result"].html = "error " + req.text,
          data={'x': 0, 'y': 1},

Reading a binary file:

from browser import ajax

def read(f):
    data =
    assert isinstance(data, bytes)

req = ajax.get("", mode="binary",

File upload

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


<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/", f,

    <input id="choosefiles" type="file" multiple="multiple" />
<button id="upload">Upload</button>