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.)
This does the trick for me:
from flask import Flask, redirect
app = Flask(__name__)
@app.route('/toexample')
def to_example():
response = redirect("http://www.example.com", code=302)
headers = dict(response.headers)
headers.update({'X-Custom-Header1': 'value1', 'X-Custom-Header2': 'value2'})
response.headers = headers
return response
This works for me on Flask v0.10.1. Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With