archae0pteryx archae0pteryx - 2 months ago 27
Javascript Question

Working with time in Python + Flask

Best way to display UTC in realtime with Flask?

I've got a little app that I would like to display UTC down to the ms. I have tried hacking together something with flask-moment (moment.js) but the refresh interval is only per/min. Here's what I've got:

app.py:



import os
import json
import requests

from functools import wraps
from flask import Flask, request, jsonify, session, redirect, render_template, send_from_directory

from flask_bower import Bower
from flask_moment import Moment
app = Flask(__name__)
app.debug = True

app.secret_key = "supersecretkey"

Bower(app)
moment = Moment(app)

@app.route('/')
def index():
return render_template('/index.html')

if __name__ == "__main__":
app.run()


templates/index.html



<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=utf-8>
{{ moment.include_jquery() }}
{{ moment.include_moment() }}
</head>
<body>
<h1>{{ moment().format('xxx') }}</h1>
</body>
</html>


My question is exacly: What is the proper way to render this clock with milliseconds? That is always running?

Answer

This JS snippet should refresh the unix timestamp (down to milliseconds) to an html element with id="timestamp"; e.g., <h1 id="timestamp"></h1>, every 100ms.

var update = function () {
   // using jQuery (really not a must):
   $("#timestamp").html(moment().format('x'));
   // or without jquery
   document.getElementById("timestamp").innerHTML = moment().format('x');
};

$(document).ready(function(){
    setInterval(update, 100);
});

If you already use jQuery, the first line in the update function should work, for strict JS, use the lower. As @albert suggested, use the right tool for the job, this is a strictly frontend update, on the client side.