2012-08-03 79 views
1

我有一个简单的Flask应用程序,它包含几个基本视图。其中一种观点称为结果。它所做的是使用GET获取URL参数,然后使用这些参数完成一堆操作,最后使用render_template()呈现模板并将计算值传递给它。根据参数将视图路由到另一个URL

渲染,结果URL看起来是这样的:

http://127.0.0.1:5000/result?s=abcd&t=wxyz 

我想要做的是,而不是结果视图下呈现模板,我想重定向到一个新的视图(让我们将其称为最终),将计算的值与重定向一起传递,并从那里呈现模板。为什么要这样做?因为我想最终的URL看起来像这个:

http://127.0.0.1:5000/final/abcd 

我很抱歉,如果标题是有点含糊。

回答

2

说,“ABCD”在最后的URL可以是实际的结果,最简单的解决方案:

@app.route("/result") 
def calculate_result(): 
    s, t = request.args.get("s"), request.args.get("t") 
    # Calculate result with s and t 
    return redirect(url_for(".display_results", result=result)) 

@app.route("/final/<result>") 
def display_results(result): 
    return render_template("results.html", result=result) 

如果不能,那么你可以使用session代替:

@app.route("/result") 
def calculate_result(): 
    s, t = request.args.get("s"), request.args.get("t") 
    # Calculate result with s and t 
    session["result"] = result 
    return redirect(url_for(".display_results", result=result)) 

@app.route("/final/abcd") 
def display_results(): 
    result = session.get("result") 
    return render_template("results.html", result=result) 
+0

我尝试使用第二种方法,无济于事。该URL已成功显示,但结果(calculate_result()存储3个变量,其中两个是字典)不会在会话中结转。此外,模板已呈现但未呈现。该页面不包含CSS,并且所有传递的变量都是无类型的。 – 2012-08-04 13:06:42

+0

@ Cyph0n - 你有没有在你的代码中设置['SECRET_KEY'](http://flask.pocoo.org/docs/api/#flask.Flask.secret_key)?如果你没有一套会议,会议将无法正常工作。 – 2012-08-04 13:45:09

相关问题