深度阅读

How to retrieve GET and POST parameters in Flask

作者
作者
2023年08月22日
更新时间
12.89 分钟
阅读时间
0
阅读量

To retrieve GET and POST parameters in Flask, you can use the request object provided by Flask. Here are some examples:

GET parameters:

from flask import Flask, request

app = Flask(__name__)

@app.route('/get')
def get_parameter():
    param = request.args.get('param_name')
    # use param variable as needed
    return "The parameter is: {}".format(param)

In this example, we define a route function called get_parameter that retrieves a GET parameter called param_name using request.args.get(). We then use the retrieved parameter and return it as a string in the HTTP response.

POST parameters:

from flask import Flask, request

app = Flask(__name__)

@app.route('/post', methods=['POST'])
def post_parameter():
    param = request.form.get('param_name')
    # use param variable as needed
    return "The parameter is: {}".format(param)

In this example, we define a route function called post_parameter that retrieves a POST parameter called param_name using request.form.get(). We then use the retrieved parameter and return it as a string in the HTTP response.

Note that for POST parameters, you need to specify the allowed HTTP methods using the methods keyword argument in the @app.route decorator, as shown in the example above.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。