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

Question:

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.

Asked By: moravec

||

Answers:

You need to specify the msg parameter:

@app.route('/msg/<msg>')
def display_msg(msg):
    return msg
Answered By: Laurent LAPORTE

You can use a global variable to store the message and return to a fixed url.

Edit: I updated display_msg() to use a default argument.

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


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

Hope this helped you.

NOTE:Please don’t use this answer! what happens when multiple clients connect to your server and access the same route at once! they will actually share data between then!

Answered By: nipunasudha

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.

Answered By: moravec
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.