I have a Flask app with blueprints. I have a function that fetches a user’s profile image and returns it as a base64 string of text (too big to store in session). I use this in the html template navbar to show the user’s profile image.
I’m having difficulty sharing this image value across all html templates. I could not get context_processor method to work as it seemed to call the function immediately, versus when I call the function specifically after they’ve logged in.
My function:
def get_user_photo():
# retrieves logged in user's profile picture
try:
sql = """
SELECT picture_data FROM ps_image WHERE emplid = %s
"""
swipe = Database()
res = swipe.execute_select_ps(sql, params=[session["user_emplid"]])
if "status" in res and res["status"] == "success":
if "data" in res and len(res["data"]) > 0:
images = res["data"]
for img in images:
return img["picture_data"]
else:
logging.error(
f"No user photo found for {session['user_name']} [{session['user_emplid']}]: {res['status']}"
)
return "none"
else:
logging.error(
f"Error getting user photo for {session['user_name']} [{session['user_emplid']}]: {res['status']}"
)
return "none"
except Exception as e:
logging.error("Error getting user photo for - {}".format(repr(e)))
return "none"
And this is where I call that function after the user has logged in:
@page_blueprint.route("/", methods=["GET"])
def landing_page(url_params=None):
# debug session data
for k, v in session.items():
logging.debug(f"-> {k}: {v}")
if "logged_in" not in session:
return redirect(url_for("page_blueprint.login_page"))
user_photo = get_user_photo()
#
# how can i now pass user_photo to all blueprints/templates to use?
#
if "sso" in request.args and request.args.get("sso") != "":
# Take user to main home page
return render_template("/index.html", sso=request.args.get("sso"))
else:
# Take user to main home page
return render_template("/index.html")