url_for
生成应用程序中定义的路由的URL。没有(或者可能不应该有)原始html文件被提供,尤其是在templates文件夹之外。每个模板都应该由Jinja呈现。要显示或发布表单的每个位置都应该通过应用程序上的路由进行处理和生成。
在这种情况下,您可能希望有一条路径,既可以在GET时呈现表单,也可以在POST时处理表单提交。
__init__.py
:
from flask import Flask, request, url_for, redirect, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/cool_form', methods=['GET', 'POST'])
def cool_form():
if request.method == 'POST':
# do stuff when the form is submitted
# redirect to end the POST handling
# the redirect can be to the same route or somewhere else
return redirect(url_for('index'))
# show the form, it wasn't submitted
return render_template('cool_form.html')
templates/index.html
:
<!doctype html>
<html>
<body>
<p><a href="{{ url_for('cool_form') }}">Check out this cool form!</a></p>
</body>
</html>
templates/cool_form.html
:
<!doctype html>
<html>
<body>
<form method="post">
<button type="submit">Do it!</button>
</form>
</html>
我不知道你的表单和路由实际上是做什么的,所以这只是一个例子。
如果需要链接静态文件,请将它们放在
static
文件夹,然后使用:
url_for('static', filename='a_picture.png')