1

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()
5
  • is this a web application? Commented Jan 22, 2013 at 19:08
  • Yes it is a web application. Commented Jan 22, 2013 at 19:12
  • Why don't you use JavaScript's file I/O mechanism, assuming you're working on server code? Commented Jan 22, 2013 at 19:22
  • It would be helpful to any responders if you provided some more details and a sample workflow to clarify your application boundaries, as you list both client-side (JavaScript) and server-side (PHP, Python/Django) technologies which are not directly interoperable -- as @ben336 mentioned, normally a user would submit some data via JS to the server, and your PHP or Python script would generate the file and make it available for download. Commented Jan 22, 2013 at 19:57
  • client side would be good as i dont have a server yet setup Commented Jan 22, 2013 at 20:14

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

6 Comments

You're ignoring the requirement to write to the file based on data derived from the javascript code. You can't just link to a pre-existing file.
umm no, that link doesnt hit against a server, its entirely selfcontained. the data is encoded in base64 as part of the url, all modern browsers accept this
+1 for the detailed client-side information, but the OP needs to clarify the system boundaries -- it reads like he wants it done on the client side, but I'm not sure if that's the real intention.
I'll be curious to see your example. My understanding is there's not an easy way to generate text files on the fly and convert them to the DATA-URI like this in pure JS. If you demonstrate a simple way I will certainly +1 and revise my answer to acknowledge this as a solution.
+1 for the example. client side would be good as i dont have a database server yet setup
|
0

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

6 Comments

why? you can generate both binary and text data in javacript
but you can't write to a file in JS, at least not in any current browser other than Chrome. See my edit.
assuming thats all true, you still cant write to a client's filesystem from the server so they would have to download the file from a link. and if you were going to make them download the file like that anyways, you can generate a dataURI in javascript to accomplish the same goal without any server side interaciton
I'm sorry, you're not making much sense to me. I'm not trying to write to the client file system. My understanding of the goal is to take information generated by javascript and write that data to a file. Since there is no reliable way to do that onto the clients machine, that will have to be done on the server. Since it requires data from the JS code, that will have to be done with an Ajax call. The user can then download the file from the server if necessary. Though its not clear the user needs to see the file at all. The purpose of the file is not specified.
there is a reliable way to create a link for the user to download in javascript, its called a data URI see my edit
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.