Python Forum

Full Version: Flask redirect(request.url) returns None
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

Currently building a small web interface and getting a little confused here:

import os
from flask import Flask, flash, request, redirect
from flask import url_for, render_template, send_from_directory
from werkzeug.utils import secure_filename

UPLOAD_FOLDER = 'uploads'
ALLOWED_EXTENSIONS = set(['xlsx', 'docx'])

app = Flask(__name__)
app.secret_key = "Hi there"
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route('/')
def index():
    return render_template('report.html')


def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        if file.filename == '':
            flash('No file selected')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))
            return render_template('run_report.html')
    return 'Something was not caught'
          
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


if __name__ == '__main__':
    app.run(debug=True)
So I am using the code from the Flask docs, but I a little confused as to what the line:
return redirect(request.url)
is actually returning. I added the return line 'Something was not caught' to try to help me. To me it looks like the return is simply redirecting back to the original url that called it, but it doesn't appear to be capturing the way I was expecting, because if I just click the submit button, I expect it to give a flash message and redirect to the original page. None of this is happening, instead I am getting this page:
Quote:builtins.TypeError
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

Traceback (most recent call last)
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1816, in full_dispatch_request
return self.finalize_request(rv)
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1831, in finalize_request
response = self.make_response(rv)
File "/Users/rki23/anaconda3/lib/python3.7/site-packages/flask/app.py", line 1957, in make_response
'The view function did not return a valid response. The'
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

My suspicions all revolve around my not understanding the "redirect(request.url)" and what it is trying to do. My work around is to create an error page redirecting to the file upload page with a message to try uploading the file again. Whilst this may well be a better way to handle this, I suspect it isn't and is just a working workaround.

EDIT: I added the line:
return 'Something was not caught'
to see where things were being missed, it was not there when the error page came. My question is still valid that I don't understand what is being redirected and why it is not picking up the error before the end of the initial if statement.
What if you change it to this, and see what it's trying to return as a response?
response = redirect(request.url)
return response