【问题标题】:How to pass a URL parameter using python, Flask, and the command line如何使用 python、Flask 和命令行传递 URL 参数
【发布时间】:2016-07-22 06:20:26
【问题描述】:

我在使用 request.args.get 传递 URL 参数时遇到了很多麻烦。

我的代码如下:

from flask import Flask, request
app= Flask(__name__)

@app.route('/post?id=post_id', methods=["GET"])
def show_post():
    post_id=1232
    return request.args.get('post_id')

if __name__=="__main__":
     app.run(host='0.0.0.0')

保存后,我总是在命令行输入python filename.py,在命令行返回见Running on http://0.0.0.0:5000/(按CTRL+C退出),然后输入url(http://ip_addres:5000/post?id=1232 ) 在 chrome 中查看它是否会返回 1232,但它不会这样做!请帮忙。

【问题讨论】:

    标签: python http command-line flask


    【解决方案1】:

    @987654321@ 就是你要找的。​​p>

    @app.route('/post', methods=["GET"])
    def show_post()
        post_id = request.args.get('id')
    

    request.args 是获取所有 GET 参数并构造 @987654322@ 像这样 MultiDict([('id', '1232'),]) 所以使用 get 你可以 get id

    【讨论】:

    • 非常感谢!请问那个网址是什么?
    • 好的,很酷!:D 非常感谢!您的回答同样有帮助!现在我不仅可以使用你们提供的代码,还可以了解它在做什么:)
    【解决方案2】:

    您应该将查询参数排除在路由之外,因为它们不是路由的一部分。

    @app.route('/post', methods=['GET'])
    def show_post():
        post_id = request.args.get('id')
        return post_id
    

    request.args 是一个字典,包含在 URL 中传递的所有查询参数。

    【讨论】:

    • 请问 URL 是什么?非常感谢!
    • URL 仍然是http://<IP Address>:5000/post?id=1232id 是一个查询参数,将出现在request.args 字典中,值为1232。注意我编辑了上面的答案以更正参数的名称。
    • 所以基本上,request.args.get('id') 会自动在 url 中插入参数?
    • 不,一点也不。您输入 URL http://127.0.0.1:5000/post?id=1232。 Flask 将切断查询字符串?id=1232 并匹配实际路径/post。该路径被路由到show_post 函数。 request.args 是一个字典,包含与 URL 一起传递的所有查询参数,在本例中是键 id 和值 1232request.args 这里将是一个看起来像这样的字典:{"id": "1232"}
    • @SAS 请也看看我的回答
    猜你喜欢
    • 2016-03-25
    • 2013-06-06
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2016-02-22
    • 2023-03-25
    • 2012-10-04
    • 2019-10-27
    相关资源
    最近更新 更多