python - 使用 Python Flask 在网页上显示时间
问题描述
我有一个任务是用烧瓶构建一个简单的网页。我已经让它工作了,并且到目前为止我的模板中都有我需要的一切。我不知道如何在我的页面上显示日期时间。我是将日期时间单独放在模板中,还是将其放在基本的python代码中?我的说明说只使用标准的 python 日期时间函数。但是当我测试我的页面时它没有显示。
from flask import Flask
from flask import render_template
import datetime
app = Flask(__name__)
@app.route('/')
def index():
return show_home()
def show_home():
return render_template('index.html')
@app.route('/ingredients/')
def ingredients():
return show_ingredients()
def show_ingredients():
return render_template('ingredients.html')
@app.route('/cooking_instructions/')
def cook_it():
return show_cook_it()
def show_cook_it():
return render_template('cooking_instructions.html')
解决方案
您可以render_template
像这样将日期时间的字符串表示形式传递给函数:
from datetime import datetime
@app.route('/example')
def example():
return render_template('template.html', datetime = str(datetime.now()))
然后,您可以使用语法访问模板中的变量{{ datetime }}
。当然,您可以使用strftime
datetime 对象上的方法自定义您的 datetime 在模板中的外观。
这将不是动态的,因此一旦模板呈现日期时间将不会更新。如果您正在寻找计数时钟,则需要用 javascript 编写该代码。查看此示例HTML 显示当前日期
推荐阅读
- javascript - MongoDB 按月分组
- reactjs - 如何将管理面板添加到现有 ASP.NET Core MVC 项目
- java - 在 Java 中执行非线程安全可选操作的最快方法
- spring - Maven Failsafe 集成测试类路径
- javascript - Push duplicate items into a separate array in Javascript with for loop?
- echo - KSH:处理命令时显示等待消息
- c# - C#异步取消异常
- php - 使用Ajax时如何为A标签参数添加值
- python - 一天的 Apache Beam 窗口化
- r - 将 DNAStringSet 转换为 R 中的元素列表?(seq[[1]][["seq"]] 中的错误:R 中的下标越界)