Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask (Python): Pass input as parameter to function of different route with fixed URL

Tags:

python

flask

How do I get the user input submitted on the form to be displayed on a fixed URL?

@app.route('/', methods=['GET','POST'])
def main():
    if request.method == 'POST':
        msg = request.form['message']
        return redirect(url_for('display_msg', msg=msg))
    else:
        return form


@app.route('/msg')
def display_msg(msg):
    return msg

When submitting the form, I get the following error:

TypeError: display_msg() missing 1 required positional argument: 'msg'

This code actually works fine if I initialize msg as a global variable and then do global msg at the top of main, but it will not allow me to pass msg as a parameter to display_msg.

Another way this will work is if I change @app.route('/msg') to @app.route('/<string:msg>'), but this will change the URL to whatever the user submitted on the form which is not what I want. I want the URL to be fixed.

like image 965
moravec Avatar asked Oct 21 '25 12:10

moravec


1 Answers

Since the data from msg is already stored in the request object, rather than passing it as a parameter to display_msg, it can be accessed as follows:

@app.route('/msg')
def display_msg():
    return request.args.get('msg')

The TypeError occurred because the keyword arguments for url_for are passed to the request object and not as parameters to display_msg.

like image 83
moravec Avatar answered Oct 23 '25 00:10

moravec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!