Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask and AJAX with JQuery

from flask import Flask, jsonify, render_template, request
import time

app = Flask(__name__)


@app.route("/")
def main():
    return render_template("main.html", reload=time.time())


@app.route("/api/info")
def api_info():
    info = {
        "ip": "127.0.0.1",
        "hostname": "everest",
        "description": "Main server",
        "load": [3.21, 7, 14],
    }
    return jsonify(info)


@app.route("/api/calc")
def add():
    a = int(request.args.get("a", 0))
    b = int(request.args.get("b", 0))
    div = "na"
    if b != 0:
        div = a / b
    return jsonify(
        {
            "a": a,
            "b": b,
            "add": a + b,
            "multiply": a * b,
            "subtract": a - b,
            "divide": div,
        }
    )
$(function() {
    $.ajax({
        url: '/api/info',
        success: function(data) {
            console.log('get info');
            $('#info').html(JSON.stringify(data, null, '   '));
            $('#description').html(data['description']);
        }
    });
 
    $('#calc').click(function() {
        $('#info').css('display', "none");
        $('#description').css('display', "none");
        //console.log(url);
        $.ajax({
            url : '/api/calc?a=' + document.getElementById('a').value + '&b=' + document.getElementById('b').value,
            success: function(data) {
                $('#add').html(data['a'] + ' + ' + data['b'] + ' = ' + data['add']);
                $('#subtract').html(data['a'] + ' - ' + data['b'] + ' = ' + data['subtract']);
                $('#multiply').html(data['a'] + ' * ' + data['b'] + ' = ' + data['multiply']);
                $('#divide').html(data['a'] + ' / ' + data['b'] + ' = ' + data['divide']);
            }
        });
    });
})
<html>
<head>
</head>
<body>
<input type="number" id="a">
<input type="number" id="b">
<button id="calc">Calc</button>
<div id="results">
   <div id="add"></div>
   <div id="subtract"></div>
   <div id="multiply"></div>
   <div id="divide"></div>
</div>

<pre id="info"></pre>
<div id="description"></div>

<script src="/static/jquery-3.1.1.min.js"></script>
<script src="/static/math.js?r={{reload}}"></script>
</body>
</html>
import ajax_jquery
import pytest


@pytest.fixture()
def web():
    return ajax_jquery.app.test_client()


def test_main_page(web):
    rv = web.get("/")
    assert rv.status == "200 OK"
    assert rv.headers["Content-Type"] == "text/html; charset=utf-8"
    assert b'<button id="calc">Calc</button>' in rv.data


def test_api_info(web):
    rv = web.get("/api/info")
    assert rv.status == "200 OK"
    assert rv.headers["Content-Type"] == "application/json"
    assert rv.json == {
        "description": "Main server",
        "hostname": "everest",
        "ip": "127.0.0.1",
        "load": [3.21, 7, 14],
    }


def test_api_calc(web):
    rv = web.get("/api/calc?a=7&b=8")
    assert rv.status == "200 OK"
    assert rv.headers["Content-Type"] == "application/json"
    assert rv.json == {
        "a": 7,
        "add": 15,
        "b": 8,
        "divide": 0.875,
        "multiply": 56,
        "subtract": -1,
    }