pythonhtmlflaskserversendfile

send_filer return None or ended without a return statement


I am trying to do a aplication where the user can dowload a plot.png and a file.csv but send_files doesnt work. Here are my python code:

app = Flask(__name__)
app.USE_X_SENDFILE = True

@app.route('/', methods= ['POST', 'GET'])
def result():
    if request.method == 'GET':
        return render_template('result.html')
    elif request.method == 'POST':
             
            if request.form['submit_button'] == 'Download CSV':
                return send_file(path_or_file='name.csv', as_attachment=True, )
                

            elif request.form['submit_button'] == 'Download plot':
                return send_from_directory("static", "plot.png") #I tried with send_file and i had the same error
    else:
         return 'Error'       
    

if __name__ == '__main__':
    app.run(debug = True, host='0.0.0.0')  

And my html code:

{% extends "layout.html" %}


{% block content %}

<div class = 'wrap'>

    <form method="POST">

        <input type="submit" name="submit_button" value="Download CSV">
        <input type="submit" name="submit_button" value="Download plot">

    </form>
</div>

{% endblock %}

Both file are in the same directory that the server:

enter image description here

And the error is:

TypeError: The view function for 'result' did not return a valid response. The function either returned None or ended without a return statement.

I dont know why send_file return None or without a statement. Thanks!! :)


Solution

  • If request.form['submit_button'] is neither 'Download CSV' nor 'Download plot' result() will implicitly return None. The return value of 'Error' will only happen if request.method is neither 'POST' nor 'GET'