How can I create a function similar to current_user?

Viewed 108

In Flask, I would like to understand how to create a function that behaves similar to current_user in the sense that it is available everywhere (controllers and views) but I'm struggling to actually know what to search for to find the answer.

The closest post on SO that I've been able to find is this one, but it's for Ruby rather than Python, could someone point me in the right direction? Thanks!


What I have so far:

In my __main__.py I have this:

@app.context_processor
def foo_processor():
    def foo():
        return 'Hello World'

The result of this is that I can access {{ foo }} in my Jinja templates without having to send it through from my controller. Unfortunately, I can't access foo within my controllers, and this is what I would like to also be able to do. Do I need to import it somehow, and if I do, how?

1 Answers

If I understand this correctly, you want a variable you can use in your templates and the controllers without having to pass it into the templates each time. To do this, first, create a function to get the variable. This could be something like getting a user's setting. Then in the context processor, you pass the result of this function through. To access it in your controllers as well, create an additional variable that holds the value of the getter. Note that if the function returns different values, you may need to call the function instead of using a variable.

# create a getter function, this returns the property's value.
def get_property():
  return "Test Text"

property = get_property() # this is only to make code pretty later on.

# the context processor passes the property to the templates.
@app.context_processor
def property_processor():
  return dict(property=get_property())

In your controllers, you can access the variable created earlier.

def view():
  if property == true:
    return redirect(url_for('index'))
  else:
    return redirect(url_for('access_denied'))

Note that if your value will change, you may need to use the function instead and recall the getter each time you render a view. This would make the first if statement into if get_property() == true: instead.

Related