Bookmark and Share

JavaScript can’t access local files; this makes it troublesome to work with databases and files without including someone’s “black box” and risking all manner of compatibility and security issues you have no control over.

Required Skillsets

You need to be familiar with both Javascript and Python, and their typical execution environments, for this information to be useful to you. Both are easy languages to learn, and the web is replete with tutorial sources aimed at providing that familiarity. Database use with Python can be with SqLite, or PostgreSQL, or MySql. Again, plenty of resources out there to help with learning SQL.

Python, on the other hand, has no such problems. It can handle files and databases directly, and you have every opportunity to keep things safe and secure. Python is readily available on your typical server; Javascript is built into most browsers.

So here is a skeletal example of how to get data from JavaScript to Python and back again that doesn’t require any extra JavaScript components, and therefore puts you in complete control of whatever risks you face, including resolving any bugs without having to depend on anyone else.

You can use this to build your own communications, adding all the security and reliability tweaks you desire, or none, for private, off-net use.

If, in pursuit of the kind of inter-language linking I demonstrate here, you’re thinking “Database!”, then I would also point you to my SqLite simplifier and PostgreSQL simplifier projects.

The first thing you need is the ability to launch a Python script from within JavaScript. Here’s a simple function to do that asynchronously (a synchronous version is provided down-post, for those who want that):

// this is asynchronous - result comes back to callback later, while this returns immediately // -----------------------------------------------------------------------=======------------ function callAjax(url, callback) { var xmlhttp; // compatible with IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { callback(xmlhttp.responseText); } }"GET", url, true); xmlhttp.send(); }

Once you have that in place, you need a way to catch the returned information. This is a callback; the callAjax() function above will cause it to be called with the output of the Python script when the called URL returns it.

function cb_myCallback(theStuff) { // process theStuff here. If it's JSON data, you can unpack it trivially in Javascript, // as I will describe later. For this example, it's just text. You're going to get // back "hello, Ben" console.log(theStuff); }

You might use all that this way:

function pyRequest(upd_data,upd_callback) { var cd_url; cd_url = '/cgi-bin/' + encodeURIComponent(upd_data); callAjax(cd_url,upd_callback); }


... pyRequest("Ben",cb_myCallback); ...

So here’s what happens. pyRequest() builds a URL that can call your Python script. callAjax() actually does the calling. This all returns immediately to the calling code. Later, when the Python script has completed whatever its task is, the callback, in the example cb_myCallback(), is sent whatever the Python script emitted. Here’s a simple “hello whoever-you-say-you-are” Python script for the example call:

#!/usr/bin/python # -*- coding: UTF-8 -*- import cgi import sys def output(content): sys.stdout.write('Content-Type: text/plain\n\n') sys.stdout.write(content) form = cgi.FieldStorage() fail=0 try: myData = str(form['myData'].value) except: fail=1  else: if myData == "": fail=1 if fail == 1: output('Who are you?') raise SystemExit output('Hello, '+myData) raise SystemExit

That’s the general idea. Now, here’s the JSON part. JSON is text. The above shows you how to pass text back and forth. So, you provide the JSON to the Python script, and to the JavaScript as text. It’s just this easy:

import json pyObject = json.loads(jsonString) // now you can use the data in Python

Going the other way, you convert the Python object to a JSON string, then that’s what you return:

output(json.dumps(pythonObject)) // sends the Python variable content to javascript as JSON

That’s pretty much all there is to the process. To use this productively, you need to account for any security issues you face, but otherwise, the above can serve as the heart and soul of back-and-forth between Python and JavaScript.

Synchronous Usage

There may be times when you won’t want to use an asynchronous callback, because you can’t proceed until you have the data you asked for. In such cases, you need to use a synchronous request, which will not return (with the actual response) until the response has been received from the script. Note that in this function, I embed the URL to demonstrate a little variety in possible structuring of these types of usages:

// this is synchronous - result returns only when called script provides it // ------------------------------------------------------------------------ function syncCallAjax(spdq_myData) { var remote = '__Unset__'; var request = new XMLHttpRequest(); var remote_url; remote_url = '/cgi-bin/' + encodeURIComponent(spdq_myData);'GET', remote_url, false); // false makes the request synchronous request.send(null); if (request.status === 200) { remote = request.responseText; } return(remote); }

So go. Enjoy. :)