我无法在烧瓶上返回日期和页脚函数

时间:2020-05-23 17:07:52

标签: python html function flask

我是一个初学者,请考虑一下,因此,我需要传递页脚和日期函数,并且在某种程度上错过了重点

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()

2 个答案:

答案 0 :(得分:1)

该函数未返回任何内容,因为未调用该函数。

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

如果在/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/

答案 1 :(得分:0)

我也没有时间,但我现在可以调查一下。 我认为您迷路了,因为您有两个带有两个不同模板的视图。而且我想,到目前为止,您只想呈现一页。

所以现在您的项目应如下所示:

您的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标签研究模板继承。但是现在,请尝试以我的示例为例,以了解应该容易使用的基础知识。