Flask: How to render a template AND save request.headers info?

I am trying to save objects made available by the request.headers in my Flask app.

I want to render my index.html upon page load, but I also want to grab the visiting user’s email so I can use it for other functions / processes.

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


def find_aad():
    aad_email = request.headers.get('X-MS-CLIENT-PRINCIPAL-NAME')  # aad email
    return aad_email

If I try to run find_aad() on its own,

user_email = find_aad()  # cant run

I will get the typical error: Working outside of request context.

How can I on an initial load of the website secure these headers and save them to an object without having these errors?

Answer

You could get at it this way, perhaps:

On that first call to index, you can create a UUID for the “session” and use that as an identifier for the user, then you pass that code back inside the rendered UI elements for stashing on the client-side. Then, on every subsequent call to the backend, you send that UUID with the rest of the request.

On those subsequent requests, you can access the email value via that UUID as the key to the data structure you’re using to store client information on the backend.

This concept is the idea of a “session” with a “session id” that is common in client/server communications. Using sockets or possibly even built in or supplemental libraries for Flask would probably be a good idea instead of “rolling your own”. Sorry if I’m being unhelpful or stupid – it’s late where I’m at.

EDIT:

By request here’s some simple pseudocode for this:

from flask import Flask
import uuid

...

uuid_to_email = {}

...

@app.route('/')
def index():
    user_id = str(uuid.uuid4())
    uuid_to_email[user_id] = request.headers.get('X-MS-CLIENT-PRINCIPAL-NAME')
    return render_template('index.html', uuid=user_id) # where it is implied that you would then use the uuid in the client-side code to story it and pass it back to the endpoints you want to do that with