使用 time.time() 的当前时间在刷新 [Python] 时不会改变

current time using time.time() doesn't change on refresh [Python]

我正在使用 time 模块将 n 毫秒转换为秒并将其添加到当前时间。

from flask import Flask

currenttime = int(round(time.time() * 1000))

@app.route('/api/<seconds>')
def api_seconds(seconds):
    milliseconds = int(seconds) * 1000
    finaltime = int(currenttime + milliseconds)
    return 'Seconds: ' + seconds + '<br />' + 'Milliseconds: ' + str(milliseconds) + \
       '<br />' + 'Time: ' + str(currenttime) + '<br />' + 'Final Time: ' + str(finaltime)

这成功 returns 时间在 运行 脚本时,但在刷新时不会更改为当前时间。我必须停止脚本并重新运行它以便刷新时间。我怎样才能让它显示当前时间?提前致谢。

currenttime 将在首次加载脚本时进行评估,但不会在并发调用 api_seconds 时重新评估,因为您的应用程序已经加载。您可以将 currenttime 的计算移到 api_seconds 方法中,它应该每次都执行。

您在 flask 应用程序运行时设置 currenttime,并且在应用程序重新启动之前不会更新。我会尝试将 currenttime 放入您的路由函数

from flask import Flask
import time

@app.route('/api/<seconds>')
def api_seconds(seconds):
    currenttime = int(round(time.time() * 1000))

    milliseconds = int(seconds) * 1000
    finaltime = int(currenttime + milliseconds)
    return 'Seconds: ' + seconds + '<br />' + 'Milliseconds: ' + str(milliseconds) + \
       '<br />' + 'Time: ' + str(currenttime) + '<br />' + 'Final Time: ' + str(finaltime)