#StackBounty: #http #flask #http-headers #werkzeug What is the best practice for changing headers in a Flask request?

Bounty: 50

I have a Flask app that uses a custom decorator to verify an AWS Cognito login token passed in an HTTP header attribute. The process includes refreshing the token (which is beyond the scope of this question). Once I get the refreshed token, I would like to update the header attribute to include the refreshed token and exit. Since the Flask/Werkzeug request.headers property is immutable, I can’t update it by normal means.

How can I update the headers in the context of this decorator? Is there a better way that I am not thinking of?

Here’s some sample code that demonstrates the issue:

def login_required(f):
    def decorated_function(*args, **kwargs):
        token = request.headers.get('X-MyApp-Auth')
        if not token:
            return redirect(url_for('login', next=request.url))
        # Test for expired token (pseudocode)
        if expired(token):
            # Refresh the token (pseudocode)
            new_token = refresh(refresh_token)
            # This is the part where the immutability gets me stuck
            request.headers.set('X-MyApp-Auth', new_token)
        return f(*args, **kwargs)
    return decorated_function

Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.