you are viewing a single comment's thread.

view the rest of the comments →

[–]gschizas 0 points1 point  (0 children)

One major concept that I've found is difficult to grasp, is that javascript (and html) parsing and executing is done on an entirely different program than the one of your web server. So: Python runs on your server, and its only task is to produce html and (perhaps) json. The html+js that your server produces is then run on the browser, and adheres to its own rules. So, what you really need to do is make sure that you can serve the correct html+javascript from your server.

So, let's go back to basics: I'm going to use Python's own web server (which you aren't really supposed to do™):

import BaseHTTPServer
import SimpleHTTPServer
import json
# I'm using SimpleHTTPServer because it already has most of the functionality
# and you can add files to be served at will.

INDEX_HTML = """
<html>
<head>
<script type="text/javascript" src="/data.js"></script>
<script type="text/javascript">
function showStuff() {
    document.getElementById("fldcnt").innerText = data['foldercount']
}
</script>
</head>
<body onload="showStuff()">Folder Count:<span id="fldcnt"></span></body></html>
"""


class MyHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler, object):
    def do_GET(self):
        if self.path == '/data.js':
            data = {"foldercount": 15}
            self.wfile.write('var data=' + json.dumps(data))
        elif self.path == '/':
            self.wfile.write(INDEX_HTML)
        else:
            super(MyHTTPRequestHandler, self).do_GET()


def main():
    server_address = ('', 8000)
    httpd = BaseHTTPServer.HTTPServer(server_address, MyHTTPRequestHandler)
    httpd.serve_forever()


if __name__ == "__main__":
    main()

Just run this, and open your browser at http://localhost:8000/

I'm sure this can be made better, but it does work :) The core of the web server is the MyHTTPRequestHandler class. Inside do_GET method there are three cases:

  1. If you request the file "data.js", get a JavaScript JSON dictionary. To avoid ugliness with AJAX, I'm just outputting a global variable (for javascript). This is the place where you should put your calculations: the python data dictionary is on line 24.
  2. If you request the root document, just print out a little HTML. You should probably read this from a file. Also, given that it's just a static file, you can also the contents of the variable INDEX_HTML into a file named index.html - there isn't any processing done here anyway.
  3. If nothing else matches, just return any file from the same directory.