Search code examples
pythonflaskwerkzeug

Werkzeug(Flask) response with redirect not working


I'm building a simple Flask application and I want to return redirect response. Also, I want to maintain total control over headers.

This is what I've got so far:

from flask import Flask
from werkzeug.wrappers import Response

app = Flask(__name__)

@app.route('/toexample')
def to_example():

    headers = {
            'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate',
    }

    return Response('www.example.com', status_code=302, headers=headers)

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

I get an error:

TypeError: __init__() got an unexpected keyword argument 'status_code'

Ok, it looks like status_code doesn't exist on __init__(), but what is the right way of doing this?

What I ultimately want is a link that a user would click but again, I want to maintain control over headers(Connection, Cookies, Referer, etc.)


Solution

  • I had to add Location to headers. Also, status_code is wrong, it should've been status=302.

    Working example:

    from flask import Flask
    from werkzeug.wrappers import Response
    
    app = Flask(__name__)
    
    @app.route('/toexample')
    def to_example():
    
        headers = {
                'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:39.0) Gecko/20100101 Firefox/39.0',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language': 'en-US,en;q=0.5',
                'Accept-Encoding': 'gzip, deflate',
                'Location': 'http://www.example.com'
        }
    
        return Response('http://www.example.com', status=302, headers=headers)
    
    if __name__ == '__main__':
        app.run(debug=True)