【问题标题】:How to pass parameter in URL to other function in Flask如何将 URL 中的参数传递给 Flask 中的其他函数
【发布时间】:2017-11-22 05:25:31
【问题描述】:

所以基本上我希望能够输入 URL,例如http://example.com/"something",如果没有,则渲染 index.html。由于某种原因,这不起作用。 另一方面,我希望能够传递该参数,例如http://example.com/host123 并在下面的结果函数中使用它。理想情况下,最后我可以简单地输入 URL example.com/host123 并直接将我带到该页面。

@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....

【问题讨论】:

    标签: python flask pymysql


    【解决方案1】:

    从您的问题来看,如果未定义主机,您似乎正在尝试 (#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')
    

    我还展示了如何使用第二个装饰器(docs here)显式路由“host is nothing”的情况。

    如果您尝试实现#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')
    

    代码 sn-ps 未经测试,但应该可以帮助您入门。祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-27
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      相关资源
      最近更新 更多