Commits

Jonathan Eunice committed 8bca230

better comments

  • Participants
  • Parent commits 6c3eb88

Comments (0)

Files changed (2)

 
 @app.route("/data", methods=['GET'])
 def data():
+    """Primary data source for AJAX/REST queries. Get's the server's current
+    time two ways: as raw data, and as a formatted string. NB While other
+    Python JSON emitters will directly encode arrays and other data types,
+    Flask.jsonify() appears to require a dict. """
+    
+    fmt    = request.args.get('format', 'best')  # gets query parameter here; default 'best'
+    
     now    = time.time()
-    fmt    = request.args.get('format', 'best')
     nowstr = time.strftime(time_format[fmt])
 
     info = { 'value':    now,
 
 @app.route("/updated")
 def updated():
-    """Wait until something has changed, and report it."""
+    """Wait until something has changed, and report it. Python has *meh* support
+    for threading, as witnessed by the umpteen solutions to this problem (e.g.
+    Twisted, gevent, Stackless Python, etc). Here we use a simple check-sleep
+    loop to wait for an update. app.config is handy place to stow global app
+    data."""
     
     while not app.config['updated']:
         time.sleep(0.5)
     
     return render_template("index.html")
     
-def occasional_update(minsecs=5, maxsecs=20, first_time=False):
+def occasional_update(minsecs=5, maxsecs=25, first_time=False):
+    """Simulate the server having occasional updates for the client. The first
+    time it's run (presumably synchronously with the main program), it just
+    kicks off an asynchronous Timer. Subsequent invocations (via Timer)
+    acutally signal an update is ready."""
+    
     app.config['updated'] = not first_time
     delay = random.randint(minsecs, maxsecs)
     threading.Timer(delay, occasional_update ).start()
+    
 
 if __name__ == "__main__":
+    # start occasional update simulation
     occasional_update(first_time=True)
     
     # start server and web page pointing to it
     port = 5000 + random.randint(0, 999)
     url = "http://127.0.0.1:{}".format(port)
-    threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
+    wb = webbrowser.get(None)  # instead of None, can be "firefox" etc
+    threading.Timer(1.25, lambda: wb.open(url) ).start()
     app.run(port=port, debug=False)
 var prev_data = null;  // remember data fetched last time
 
 function load_data() {
+    // load data from /data, optionally providing a query parameter read from
+    // the #format select
 
     var format =  $('select#format option:selected')[0].value;
     var url = '/data' + (format ? "?format=" + format : "")
 }
 
 function wait_for_update() {
+    // Uses separate update notification and data providing URLs. Could be
+    // combined, but if they're separated, the Python routine that provides
+    // data needn't be changed from what's required for standard, non-long-polling
+    // web app. If they're combined, arguably over-loads the purpose of the function.
+    
     $.ajax({ url: '/updated',
-             success:  load_data,
-             complete: wait_for_update,
+             success:  load_data,        // if /update signals results ready, load them!
+             complete: wait_for_update,  // if the wait_for_update poll times out, rerun
              timeout:  60000,
            });    
 }
 
 function display_data(data) {
-    if (data && (data != prev_data)) {
+    // show the data acquired by load_data()
+    
+    if (data && (data != prev_data)) {      // if there is data, and it's changed
+        
+        // update the contents of several HTML divs via jQuery
         $('div#value').html(data.value);
         $('div#contents').html(data.contents);
+        
+        // remember this data, in case want to compare it to next update
         prev_data = data;
+        
+        // a little UI sparkle - show the #updated div, then after a little
+        // while, fade it away
         $("#updated").fadeIn('fast');
         setTimeout(function() {  $("#updated").fadeOut('slow');  }, 2500);
-
     }
 }
 
 $(document).ready(function() {
+    // inital document setup - hide the #updated message, and provide a
+    // "loading..." message
     $("div#updated").fadeOut(0);
     $("div#contents").append("awaiting data...");
+    
+    // load the initial data (assuming it will be immediately available)
     load_data();
-    wait_for_update();
+    // wait_for_pdate();
 });