基本烧瓶:在视图

时间:2015-07-06 20:46:22

标签: python flask

我在这里关注Miguel Grinberg的Flask教程:

http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates

我试图添加帮助函数,并根据此处的响应:

http://stackoverflow.com/questions/30677420/basic-flask-adding-helpful-functions

应该能够在我的视图文件中定义一个辅助函数并使用它。例如,我的app/views.py目前是:

from flask import render_template
from app import app

@app.route("/")
@app.route("/index")
def hey():
    return 'hey everyone!'
def index():
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('index.html', title='Home', user=user)

我的app/templates/index.html文件目前是:

<html>
    <head>
        <title>{{ title }} - microblog</title>
    </head>
    <body>
        <h1> {{ user.saying }}, {{ user.nickname }}!</h1>
    </body>
</html>

然而,当我运行本地服务器时,它呈现为"hey everyone!"并且就是这样。我的{{ user.nickname }}似乎没有被提起。

我取出了{{ user.saying }}部分并重新启动了本地服务器。它仍然说"hey everyone!"显然它没有根据我输入的内容进行更新。任何想法为什么会发生这种情况?

谢谢, bclayman

2 个答案:

答案 0 :(得分:1)

这对我有用:

<html>
    <head>
        <title>{{ title }} - microblog</title>
    </head>
    <body>
        <h1> {{ user["saying"]}}, {{ user["nickname"]}}!</h1>
    </body>
</html>
编辑:哦,做到这一点:

def hey():   # <-- this function was being called not index()
    return 'hey everyone!'

@app.route("/")
@app.route("/index")
def index(): # <-- this function will now be called b/c it is directly under routes
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('layout.html', title='Home', user=user)

if __name__ == '__main__':
    app.run(debug=True)

答案 1 :(得分:1)

这是因为函数index()永远不会被路由到。删除hey()函数。

@app.route("/")
@app.route("/index")
def hey():   # <-- the decorators (@app.route) only applies to this function
    return 'hey everyone!'
def index(): # <-- this function never gets called, it has no decorators
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('index.html', title='Home', user=user)

装饰器适用于以下功能。因此,尝试将装饰器移动到它们应该路由到的函数之上,如下所示:

from flask import render_template
from app import app

def hey():   
    return 'hey everyone!'

@app.route("/")
@app.route("/index")
def index(): 
    user = {'nickname': 'Ben', 'saying': hey()}
    return render_template('index.html', title='Home', user=user)