render_template()只需1个参数

Gan*_*g L 3 python flask

当我点击提交以获取以下视图时,我收到500错误.为什么我会收到此错误,如何解决?

from flask import Flask, render_template
from flask import request, jsonify

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def homepage():
    if request.method == 'POST':
        f1 = request.form['firstVerb']
        f2 = request.form['secondVerb']
        return render_template('index.html', f1, f2)
    return render_template('index.html')

if __name__ == "__main__":
    app.run();
Run Code Online (Sandbox Code Playgroud)
<form class="form-inline" method="post" action="">
<div class="form-group">
    <label for="first">First word</label>
    <input type="text" class="form-control" id="first" name="firstVerb">
</div>
<div class="form-group">
    <label for="second">Second Word</label>
    <input type="text" class="form-control" id="second" name="secondVerb" >
</div>
<button type="submit" class="btn btn-primary">Run it</button>
</form>

{{ f1 }}
{{ f2 }}
Run Code Online (Sandbox Code Playgroud)

met*_*ter 17

首先,当您收到500错误时,您应该考虑使用调试模式运行应用程序.你正在构建这个应用程序,你正在调试,没有理由保持它以隐藏你发生的事情.

if __name__ == "__main__":
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)

现在,这会让你更加精彩:

127.0.0.1 - - [08/Jul/2015 14:15:04] "POST / HTTP/1.1" 500 -
Traceback (most recent call last):
...
  File "/tmp/demo.py", line 11, in homepage
    return render_template('index.html', f1, f2)
TypeError: render_template() takes exactly 1 argument (3 given)
Run Code Online (Sandbox Code Playgroud)

有你的问题.您应该参考文档render_template并查看它实际上只接受一个位置参数(模板名称),但其余参数(in **context)将作为关键字参数提供.否则在模板中无法引用您传入的变量(您必须为它们指定显式名称),因此将该调用修复为:

    return render_template('index.html', f1=f1, f2=f2)
Run Code Online (Sandbox Code Playgroud)

那应该可以解决你的问题.

为了将来参考,可以通过阅读Flask文档来解决这些问题.另外,请完成整个Flask教程,以帮助您掌握此框架的基础知识.