我无法返回flask上的日期和页脚函数

2024-10-01 00:28:33 发布

您现在位置:Python中文网/ 问答频道 /正文

im a beginner, take that in cosideration, so, i need to pass the the footer and date functions and i somehow missing the point here

from flask import Flask, render_template
from datetime import datetime


app = Flask("Timer Workout")



@app.route("/")
def Landing():
    return render_template("Landing_Page.html")

def footer():
    footerdb = open("footer.txt")
    for i in range (3):
        footerdb.write("footer.txt" + " by Carlos ")
    footerdb.close()
    return render_template("Landing_Page.html", footerdb)

这里也是一样,我不能返回日期函数,我不知道应该怎么做。谢谢你的帮助。非常感谢

    @app.route("/index.html/")
def Home():
    current_time = datetime.datetime.now()
    return render_template("index.html", current_time = current_time)





if "Timer Workout" == "__main__":
    app.run()

Tags: andtheinappdatetimereturntimedef
2条回答

函数没有返回任何内容,因为它没有被调用

您希望在哪里返回日期/时间

如果在/index.html中,您应该执行以下操作:

@app.route("/index.html/")
def Home():
    current_time = datetime.datetime.now()
    return render_template("index.html", current_time=current_time)

然后在模板中,您可以在HTML代码中添加变量,例如:

Current Date and Time: {{ current_time }}}

基本上,您可以在python主脚本中定义变量值。将它们作为参数传递给render_template函数,然后在模板中与{{ your_var }}一起使用

看看这里:https://jinja.palletsprojects.com/en/2.11.x/templates/

我也没有时间,但我现在可以调查一下了。 我想你是迷路了,因为你有两个视图和两个不同的模板。我想,就目前而言,您只需要渲染一页

现在你的项目应该是这样的:

你的mainscript.py是:

from flask import Flask, render_template
from datetime import datetime

app = Flask("Timer Workout")

@app.route("/")
def Landing():
    return render_template("Landing_Page.html")

def footer():
    footerdb = open("footer.txt")
    for i in range (3):
        footerdb.write("footer.txt" + " by Carlos ")
    footerdb.close()
    return render_template("Landing_Page.html", footerdb)

@app.route("/index.html/")
def Home():
    current_time = datetime.datetime.now()
    return render_template("index.html", current_time = current_time)

if "Timer Workout" == "__main__":
    app.run()

然后您应该有两个HTML文件,Landing_page.htmlindex.html

但是,我认为您正在尝试使用页脚和当前日期和时间呈现一个且仅一个页面

为此,我将给你一个应该有效的例子。只需删除你的footer()函数,它有缺陷并且没有在任何地方调用,我们将只进行一次路由来呈现一个模板

在你的mainscript.py中:

from flask import Flask, render_template
from datetime import datetime


app = Flask("Timer Workout")

@app.route("/")
def home():
    current_time = datetime.datetime.now()
    footer = "Placeholder string just for debugging"
    return render_template("index.html", current_time = current_time, footer = footer)


if "Timer Workout" == "__main__":
    app.run()

然后在index.html文件中放入如下内容:

<html>
<head>
    <title>Index page</title>
</head>

<body>
Current date/time is : {{ current_time }}
<br><br>
The footer would be just below : <br>
{{ footer }}
</body>
</html>

现在,当您访问yourwebsite.com/时,您将看到index.html正确呈现。 当然,您应该找到一种更好的方法来添加页脚,您将使用extends标记研究模板继承。但现在,请尝试我的示例,以了解应该容易操作的基础知识

相关问题 更多 >