AJAX with bottle.py

Without much further ado, here is how to create a webpage with AJAX, JQuery and Bottle.py.

Here is the web application:

from bottle import route, run, debug, template, request
import json

def add_numbers():
    """Add two numbers server side, ridiculous but well..."""
    a = request.params.get('a', 0, type=int)
    b = request.params.get('b', 0, type=int)
    return json.dumps({'result': a+b})

def index():
    return template('index.tpl', request=request)


And this is the template:

<!doctype html>
<title>jQuery Example</title>
<script type="text/javascript"
<script type="text/javascript">
  var $SCRIPT_ROOT = "{{ request.script_name }}";

<script type="text/javascript">
  $(function() {
    var submit_form = function(e) {
      $.getJSON($SCRIPT_ROOT + '_add_numbers', {
        a: $('input[name="a"]').val(),
        b: $('input[name="b"]').val()
      }, function(data) {
      return false;

    $('a#calculate').bind('click', submit_form);

    $('input[type=text]').bind('keydown', function(e) {
      if (e.keyCode == 13) {

<h1>jQuery Example</h1>
  <input type="text" size="5" name="a"> +
  <input type="text" size="5" name="b"> =
  <span id="result">?</span>
<p><a href=# id="calculate">calculate server side</a>

The code is based on the original example given inside Flask sources by Armin Ronacher. You can download both files directy from here: ajax_bottle.py, index.tpl.

This entry was tagged: python, web, jquery

Share this post:


comments powered by Disqus