nadermx nadermx - 4 months ago 18
Python Question

Check if user is anonymous for Flask-Cache `unless` argument

I am trying to cache a view unless the user is logged in.

current_user
only works inside a view though, so I'm having trouble passing it to
unless=
. How do I do this correctly?

@app.route("/")
@app.cache.cached(timeout=300, unless=current_user.is_authenticated())
def index():
return 'stuff to return'

Answer

Wrap the call in a lambda. Flask-Cache will call the function when the view is executed, rather than once when the view is defined.

@app.cache.cached(timeout=300, unless=lambda: current_user.is_authenticated)

The docs specifically say that unless should be a callable that will be executed each time.