user11235
user11235

Reputation: 147

Incorporating Python code in a JavaScript web application

I am primarily a Java and Python developer and I recently picked up JavaScript in order to design an application I am currently working on. In order to design the application, I would like to incorporate some necessary Python code into the JavaScript framework. However, I am not quite sure how to do this. The specific script I would like to implement is a file writing script in Python that takes some variables generated from the JavaScript and writes a file containing the information and formatted in some way to fit a particular text file format. Code below. I have also used PHP in the application. Is it possible to use Django to incorporate the Python code (I have never used Django before) or some other way? Thanks.

Python:

 newfile = open(newfile.txt, "w")
 newfile.write("New File")
 newfile.close()

Upvotes: 1

Views: 1470

Answers (2)

Ben McCormick
Ben McCormick

Reputation: 25718

Note: for a fully clientside solution, see Aaron's answer.


You can make a call to a serverside script in order to generate the file.

This is done using ajax (making asynchronous calls from the client to the server)

You can do this with Django

Here's a list of Django Ajax resources

Or you can do it separately, there are plenty of resources online for Ajax

About Javascripts file API

Some other people have suggested using Javascript's file writing API, but assuming I'm understanding you correctly and you're writing browser code (not Node.js) I would recommend against it. Those APIs are not yet widely supported. Here's a list of supported browsers for that API: http://caniuse.com/#feat=filesystem

Upvotes: 0

user545199
user545199

Reputation:

ok, for web applications, support for python is going to be based on whether or not the browser has python support either provided as a plugin or built in to the browser. it probably isn't a good idea to rely on this being the case for most people who view the application. If you do, its just a matter of including the script in a <SCRIPT type="text/x-python" src="path-to-your-pyfile.py"> tag in the html. As an alternative, javascript, thanks to html5 now has support to write to files with both text and binary data. See the file api here.

if there there is a problem with using the file api, you can always create a link to a file for the user to save from javascript using data URIs like so:

data:text/plain;base64,aGVsbG8gZnJvbSBhIGRhdGEgdXJpISEh

here is an example of an html file that generates files on the fly from javascript note i rolled my own base64 encoder but there are many js libraries available for this.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<SCRIPT type="text/javascript" >
var BASE_64_ALPHABET =//for encoding base64
[
 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
 '0','1','2','3','4','5','6','7','8','9','+','/'
];
var BASE_64_PAD = '=';
function valueAt(source,index)
{
    var result = null;

    if(source.charAt)
        result = source.charAt(index);
    else 
        result = source[index];

    if(result.charCodeAt)
        result = result.charCodeAt(0);

    if(result === null | result === undefined)
        return 0;

    return result;
}
function toBase64(data, offset, length)
{
    var padSize = (3-(length % 3));

    if(padSize == 3 && length != 0)
        padSize = 0;

    var bufferSize = ((4*(length-(length%3)))/3); + padSize;
    var buffer = new Array(bufferSize);

    var iterationLimit = length + (length % 3) - 1;

    var octetMask = 0xFF;
    var sextetMask = 0x3F;

    for(var sourceIndex=0,destinationIndex=0;sourceIndex<iterationLimit;sourceIndex+=3,destinationIndex+=4)
    {
        var readBlock =
        (
            ((valueAt(data, offset+sourceIndex) & octetMask) << 16) |
            ((valueAt(data, offset+sourceIndex+1) & octetMask) << 8) |
            (valueAt(data, offset+sourceIndex+2) & octetMask)
        );

        buffer[destinationIndex] = BASE_64_ALPHABET[(readBlock >>> 18) & sextetMask];
        buffer[destinationIndex+1] = BASE_64_ALPHABET[(readBlock >>> 12) & sextetMask];
        buffer[destinationIndex+2] = BASE_64_ALPHABET[(readBlock >>> 6) & sextetMask];
        buffer[destinationIndex+3] = BASE_64_ALPHABET[readBlock & sextetMask];
    }
    for(var i = 0; i < padSize; i++)
        buffer[buffer.length - 1 - i] = BASE_64_PAD;

    return buffer.join("");
}

function makeDataURI()
{
    var data = document.getElementById("datasource").value;
    var mime = document.getElementById("mimesource").value;
    alert("data:"+mime+";base64,"+toBase64(data,0,data.length));
}

</SCRIPT>
</head>
<body>
<INPUT id="datasource" type="text" value="enter your file data here"></INPUT>
<INPUT id="mimesource" type="text" value="enter your mime type here"></INPUT>
<INPUT type="button" onclick="makeDataURI();" value="Generate URI"></INPUT>
</body>
</html>

Upvotes: 2

Related Questions