Quickly Creating Ajax Web Demos

In about 50 lines of Python code, you can create the skeleton for a web demo that uses Ajax. This way you can have an interactive demo with HTML links, access to your executables and scripts, etc.; but you’re now free from the system restrictions of JavaScript (which exist for security reasons).

The reason why the 50 lines is impressive is that in order to free yourself from the system restrictions of JavaScript, your web page needs to communicate data back and forth with a web server, and potentially with a database if you have lots of persistent data. Usually you have to install and configure all sorts of servers and settings to get this working.

Since I want my demo to exist within a self-contained directory, Python’s batteries included philosophy comes to the rescue. With WSGI and SQLite, I can (1) create a minimalistic web server that delivers a JavaScript demo and can (2) select what to display from potentially massive amounts of data.

It’s just one file that runs the server. I can then open my browser to “localhost:8000” and the demo can proceed. Of course, I just placed a skeleton below. You can make things more fancy regarding Ajax and JSON as well as by using more heavy-weight WSGI implementations than wsgiref.

Update: a Vim ‘:TOhtml’ issue was fixed in the code below

from wsgiref.simple_server import make_server

ajax_html = """
<html>

<head>
<title>AJAX + wsgiref Demo</title>
<script language="Javascript">
function ajax_send()
{
    hr = new XMLHttpRequest();

    hr.open("POST", "/", true);
    hr.setRequestHeader("Content-Type",
        "application/x-www-form-urlencoded");

    hr.onreadystatechange = function()
    {
        if (hr.readyState == 4)
            document.getElementById("result").innerHTML =
                hr.responseText;
    }
    hr.send(document.f.word.value);
}
</script>
</head>

<body>
<center>
<form name="f" onsubmit="ajax_send(); return false;">
    <p>
        <input name="word" type="text">
        <input value="Do It" type="submit">
    </p>
    <div id="result"></div>
</form>
</center>
</body>
</html>
"""

def intact_app(environ, start_response):
    if environ["REQUEST_METHOD"] == "POST":
        start_response("200 OK", [("content-type", "text/html")])
        clen = int(environ["CONTENT_LENGTH"])
        return [environ["wsgi.input"].read(clen)]

    else:
        start_response("200 OK", [("content-type", "text/html")])
        return [ajax_html]

httpd = make_server("", 8000, intact_app)
httpd.serve_forever()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s