2017-06-19 129 views
-2

所以基本上我希望能够输入URL http://example.com/“东西”,如果没有什么渲染index.html。由于某种原因,这是行不通的。 另一方面,我希望能够传递该参数,例如http://example.com/host123并在下面的结果函数中使用它。理想情况下,我可以直接输入URL example.com/host123并直接进入该页面。如何将URL中的参数传递给Flask中的其他函数

@app.route('/<host>',methods= ['POST', 'GET']) 
    15 def index(host):  
    16   if host is None: 
    17     return render_template("index.html") 
    18   else: 
    19     return result(host) 
    20   print("test") 
    21 @app.route('/<host>',methods= ['POST', 'GET']) 
    22 def result(host): 
#some code.... 

回答

0

从你的问题看来你是想(#1)呈现的index.html模板,如果没有定义的主机,否则渲染不同的模板。然而,从你的代码看来,如果主机被定义,你可能实际上想要(#2)重定向到另一个端点。

如果您正在尝试#1,那么您已经非常接近。不要将结果函数作为路由,渲染并从该函数返回所需的模板,然后从视图中返回。事情是这样的:

@app.route('/',methods= ['POST', 'GET']) 
@app.route('/<host>',methods= ['POST', 'GET']) 
def index(host=None):  

    if host is None: 
     return render_template('index.html') 
    else: 
     return result(host) 

def result(host): 
    ... 
    return render_template('other_template.html') 

我还展示了如何明确路线“主机是什么”的情况下与第二装饰(文档here)。

如果您尝试实施#2,请查看Flask.redirect函数并重定向到所需的端点/ URL。请记住,您的代码当前显示了响应相同变量url路径的两个视图函数。您应该使用唯一的网址,以便您的应用程序可以解决这些问题正确(你可以找到更多关于这个here尝试是这样的:

@app.route('/',methods= ['POST', 'GET']) 
@app.route('/<host>',methods= ['POST', 'GET']) 
def index(host):  

    if host is None: 
     return render_template('index.html') 
    else: 
     return redirect(url_for('result', host=host)) 

@app.route('/result/<host>',methods= ['POST', 'GET'])  
def result(host): 
    ... 
    return render_template('other_template.html') 

代码片段没有测试过,但应该让你开始好运气

+0

感谢帮忙的人,我会尽力的。 – BeastlyBernardo

相关问题