Home > other >  Separate Flask route GET method from POST
Separate Flask route GET method from POST

Time:12-02

I have a following route for file upload.

@app.route("/upload", methods=["GET", "POST"])
def upload_file():
    form = FileUploadForm()
    if form.validate_on_submit():
        file = form.document.data
        file_name = secure_filename(file.filename)
        save_path = get_user_uploads_folder(current_user) / file_name
            return redirect(url_for("upload_file"))
        file.save(save_path)
        return redirect(url_for("list_user_files"))
    return render_template("upload_file.html", form=form)

How to separate this route, so i can have GET and POST methods in different functions with common route like so:

@app.route("/upload", methods=["GET"])
def upload_file():
    return render_template(...)

@app.route("/upload", methods=["POST"])
def upload_file():
    form = FileUploadForm()
    ...
    return redirect(...)

CodePudding user response:

This is discussed in the Flask docs. You can use the following pattern:

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

CodePudding user response:

You can check the methods in the request and then apply appropriate actions to it.

@app.route('/upload', methods = ['GET', 'POST')
def upload_file():
    if request.method == 'GET':
        return render_template(...)
    elif request.method == 'POST':
        return redirect(...)
    else:
         // do whatever you want here for exceptions
  • Related