【问题标题】:Get a variable from the URL in a Flask route从 Flask 路由中的 URL 获取变量
【发布时间】:2016-05-13 07:52:42
【问题描述】:

我有许多以 landingpage 开头并以唯一 ID 结尾的 URL。我需要能够从 URL 中获取 id,以便我可以将一些数据从另一个系统传递到我的 Flask 应用程序。我怎样才能得到这个值?

http://localhost/landingpageA
http://localhost/landingpageB
http://localhost/landingpageC

【问题讨论】:

    标签: python url flask


    【解决方案1】:

    这在文档的quickstart 中得到了回答。

    您需要一个可变 URL,通过在 URL 中添加 <name> 占位符并在视图函数中接受相应的 name 参数来创建它。

    @app.route('/landingpage<id>')  # /landingpageA
    def landing_page(id):
        ...
    

    更常见的是,URL 的各个部分用/ 分隔。

    @app.route('/landingpage/<id>')  # /landingpage/A
    def landing_page(id):
        ...
    

    使用 url_for 生成页面的 URL。

    url_for('landing_page', id='A')
    # /landingpage/A
    

    您也可以将值作为查询字符串的一部分传递,以及 get it from the request,尽管如果始终需要,最好使用上面的变量。

    from flask import request
    
    @app.route('/landingpage')
    def landing_page():
        id = request.args['id']
        ...
    
    # /landingpage?id=A
    

    【讨论】:

      【解决方案2】:

      这样的例子

      @app.route('/profile/<username>')
      def lihat_profile(username):
          return "welcome to profile page %s" % username
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 2022-07-07
        • 2012-01-03
        • 2014-03-14
        相关资源
        最近更新 更多