【问题标题】:How to obtain values of parameters of get request in flask?如何在flask中获取get请求的参数值?
【发布时间】:2024-04-27 08:30:02
【问题描述】:

我在网上找到的答案是使用request.args.get。但是,我无法让它工作。我有以下简单的例子:

from flask import Flask
app = Flask(__name__)

@app.route("/hello")
def hello():
    print request.args['x']
    return "Hello World!"

if __name__ == "__main__":
    app.run()

我在浏览器中转到127.0.0.1:5000/hello?x=2,结果得到:

Internal Server Error

The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.

我做错了什么?

【问题讨论】:

标签: python web flask get-request


【解决方案1】:

简单的答案是你没有从flask包中导入request全局对象。

from flask import Flask, request

这很容易通过在调试模式下运行开发服务器来确定自己

app.run(debug=True)

这将为您提供堆栈跟踪,包括:

print request.args['x']
NameError: global name 'request' is not defined

【讨论】:

    【解决方案2】:

    http://localhost:5000/api/iterators/opel/next?n=5

    对于之前的情况

    from flask import Flask, request
    n = request.args.get("n")
    

    可以解决问题

    【讨论】: