相关疑难解决方法(0)

传递参数时重定向

在烧瓶中,我可以这样做:

render_template("foo.html", messages={'main':'hello'})
Run Code Online (Sandbox Code Playgroud)

如果foo.html包含{{ messages['main'] }},页面将显示hello.但是,如果有一条通往foo的路线怎么办:

@app.route("/foo")
def do_foo():
    # do some logic here
    return render_template("foo.html")
Run Code Online (Sandbox Code Playgroud)

在这种情况下,获取foo.html的唯一方法是,如果我希望无论如何都要发生这种逻辑,那就是通过redirect:

@app.route("/baz")
def do_baz():
    if some_condition:
        return render_template("baz.html")
    else:
        return redirect("/foo", messages={"main":"Condition failed on page baz"}) 
        # above produces TypeError: redirect() got an unexpected keyword argument 'messages'
Run Code Online (Sandbox Code Playgroud)

那么,我怎样才能将该messages变量传递给foo路由,这样我就不必在加载之前重写该路由计算的相同逻辑代码?

python flask

43
推荐指数
2
解决办法
8万
查看次数

如何"重定向"到另一个URL并使用Flask传递列表对象

我有一个关于URL更改的基本问题.假设我有一个HTML页面http://example.com/create,其中包含带有一些输入字段的表单.从这个输入字段我想创建一个python列表,该列表应该用于生成http://example.com/show_list包含基于python列表值的列表的另一个HTML页面.

所以观点http://example.com/create是:

@app.route('/create', methods=['GET', 'POST']) 
def create():

if request.method == 'POST':
    some_list = parse_form_data_and_return_list(...)
    return render_template( "show_list.html", some_list=some_list)  #here's the problem!

return render_template( "create.html")
Run Code Online (Sandbox Code Playgroud)

假设parse_form_data_and_return_list(...)获取用户输入并返回包含某些string值的列表.我在困扰我的那条线上添加了评论.我会在一秒钟内回到它,但首先给你一个http://example.com/show_list应该在用户输入之后加载的页面模板():

{% block content %}
<ul class="list">       
  {% for item in some_list %}
    <li>
        {{ item }}
    </li>
  {% endfor %}
</ul>
{% endblock content %}
Run Code Online (Sandbox Code Playgroud)

基本上这很好用.列表值"传递"到Jinja模板,并显示列表.

如果您现在再次查看我的路由方法,您可以看到我只是在render_template显示该shwo_list页面.对我来说,这有一个缺点.该网址不会更改为http://example.com/show_list,但会保留http://example.com/create.

所以我考虑在方法调用中创建自己routeshow_list,而不是直接渲染下一个模板.像这样:create()redirect

@app.route('/show_list') …
Run Code Online (Sandbox Code Playgroud)

python flask

6
推荐指数
1
解决办法
2万
查看次数

标签 统计

flask ×2

python ×2