cfpb / django-flags

Feature flags for Django projects
https://cfpb.github.io/django-flags/
Creative Commons Zero v1.0 Universal
256 stars 31 forks source link

How to show a banner if any flag enabled #81

Closed 17lwinn closed 3 years ago

17lwinn commented 3 years ago

I have everything set up but what I want to do is show a banner saying 'your using a beta feature' when ANY flag is enabled.

How could I do this? Preferably in the template

willbarton commented 3 years ago

@17lwinn Currently there isn't a built-in way to do that without checking each flag individually.

I think you could probably use a custom condition that checks if any other flag is enabled:

from flags import conditions
from flags.sources import get_flags
from flags.state import flag_enabled

@conditions.register('any other flag is enabled')
def any_other_flag_is_enabled_condition(path, request=None, **kwargs):
    for flag in get_flags():
        try:
            if flag_enabled(flag, request=request, **kwargs):
                return True
        except conditions.RequiredForCondition:
            pass

(Note: I don't think something like any(flag_enabled(flag) for flag in get_flags()) will work because flag state checking can raise a RequiredForCondition if one of the flag's conditions requires additional keyword arguments to check.)

And then use that to enable a banner flag specifically:

FLAGS = {
    'BETA_FEATURE_NOTICE': [
        {'condition': 'any other flag is enabled'},
    ],
}

Then use it in a template:

{% load feature_flags %}
{% flag_enabled 'BETA_FEATURE_NOTICE' as beta_notice_flag %}
{% if beta_notice_flag %}
  <div>
    You're using a beta feature.   
  </div>
{% endif %}

This is all pseudo-code right now, I haven't tried it. But that's probably where I would start trying to enable a banner based on any other flag condition.

17lwinn commented 3 years ago

I'll see if this works, thanks for your help!

17lwinn commented 3 years ago

Hi sorry to reopen but where exactly would I put the condition code?

willbarton commented 3 years ago

No problem at all!

The custom condition can go in any module in your app that gets loaded when the app is ready.

So, you could put it in a myapp/flag_conditions.py module, and then in the app config class import it, something like this:

# myapp/apps.py
from django.apps import AppConfig

class MyAppConfig(AppConfig):
    def ready(self):
        import myapp.flag_conditions

By importing it, the condition will be registered and can then be used.

17lwinn commented 3 years ago

okay! thanks for your help @willbarton!