【问题标题】:How to do variable as part of url?如何将变量作为 url 的一部分?
【发布时间】:2020-01-27 09:03:15
【问题描述】:

我想要一个结构我的 GET 请求 URL 如下:

/api/results?date={YYYY-MM-DD}   
(e.g. 2019-09-20)

我试过了

@app.route('/api/results?ddate=<string:game_id>', methods=['GET'])
def get_game(game_id):
    print("game: ", game_id)
    return jsonify(game_id)

我也试过了:

@app.route('/api/results?ddate=game_id', methods=['GET'])
def get_game():
    game_id= request.args.get('ddate')
    print("game: ", game_id)
    return jsonify(game_id)

【问题讨论】:

    标签: python url flask


    【解决方案1】:

    为了补充答案,如果你坚持像以前一样去做,那么你可以如何实现它。

    @app.route('/api/results/<string:game_id>', methods=['GET'])
    def get_game(game_id):
        print("game: ", game_id)
        return jsonify(game_id)
    

    甚至可以像这样扩展您的网址

    @app.route('/api/results/<string:game_id>/games/../..', methods=['GET'])
    

    取决于偏好(请注意,.. 可以是字符串,例如结果或变量,例如 game_id,注意对于您 url 中的每个变量,必须有一个相应的参数传递给函数)。希望有帮助

    【讨论】:

      【解决方案2】:

      考虑到您的第二个代码,根据 FLASK docrequest.args.get 是带有查询字符串解析内容的 MultiDict。 (网址中问号后的部分)...所以您不再需要将此部分放在您的网址中。你的代码应该是这样的:

      @app.route('/api/results', methods=['GET'])
      def get_game():
          game_id= request.args.get('ddate')
          print("game: ", game_id)
          return jsonify(game_id)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-19
        • 2017-11-12
        • 2013-07-29
        • 2016-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多