Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a URL parameter using python, Flask, and the command line

I am having a lot of trouble passing a URL parameter using request.args.get.

My code is the following:

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')

After saving, I always type python filename.py in the command line, see Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) as the return on the command line, and then type in the url (http://ip_addres:5000/post?id=1232) in chrome to see if it will return 1232, but it won't do it! Please help.

like image 705
SAS Avatar asked Dec 02 '22 14:12

SAS


2 Answers

You should leave the query parameters out of the route as they aren't part of it.

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

request.args is a dictionary containing all of the query parameters passed in the URL.

like image 123
bdjett Avatar answered Apr 28 '23 23:04

bdjett


request.args is what you are looking for.

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

request.args is get all the GET parameters and construct Multidict like this MultiDict([('id', '1232'),]) so using get you can get the id

like image 23
Raja Simon Avatar answered Apr 28 '23 22:04

Raja Simon