|
| 1 | +import json |
| 2 | +import os |
| 3 | + |
| 4 | +from flask import Flask, render_template, request |
| 5 | + |
| 6 | +from flagsmith import Flagsmith |
| 7 | +from flagsmith.models import DefaultFlag |
| 8 | + |
| 9 | +app = Flask(__name__) |
| 10 | + |
| 11 | + |
| 12 | +def default_flag_handler(feature_name: str) -> DefaultFlag: |
| 13 | + """ |
| 14 | + Function that will be used if the API doesn't respond, or an unknown |
| 15 | + feature is requested |
| 16 | + """ |
| 17 | + |
| 18 | + if feature_name == "secret_button": |
| 19 | + return DefaultFlag( |
| 20 | + enabled=False, |
| 21 | + value=json.dumps({"colour": "#b8b8b8"}), |
| 22 | + ) |
| 23 | + |
| 24 | + return DefaultFlag(False, None) |
| 25 | + |
| 26 | + |
| 27 | +flagsmith = Flagsmith( |
| 28 | + environment_key=os.environ.get("FLAGSMITH_ENVIRONMENT_KEY"), |
| 29 | + default_flag_handler=default_flag_handler, |
| 30 | +) |
| 31 | + |
| 32 | + |
| 33 | +@app.route("/", methods=["GET", "POST"]) |
| 34 | +def home(): |
| 35 | + if request.args: |
| 36 | + identifier = request.args["identifier"] |
| 37 | + |
| 38 | + trait_key = request.args.get("trait-key") |
| 39 | + trait_value = request.args.get("trait-value") |
| 40 | + traits = {trait_key: trait_value} if trait_key else None |
| 41 | + |
| 42 | + # Get the flags for an identity, including the provided trait which will be |
| 43 | + # persisted to the API for future requests. |
| 44 | + identity_flags = flagsmith.get_identity_flags( |
| 45 | + identifier=identifier, traits=traits |
| 46 | + ) |
| 47 | + show_button = identity_flags.is_feature_enabled("secret_button") |
| 48 | + button_data = json.loads(identity_flags.get_feature_value("secret_button")) |
| 49 | + return render_template( |
| 50 | + "home.html", |
| 51 | + show_button=show_button, |
| 52 | + button_colour=button_data["colour"], |
| 53 | + identifier=identifier, |
| 54 | + ) |
| 55 | + |
| 56 | + # Get the default flags for the current environment |
| 57 | + flags = flagsmith.get_environment_flags() |
| 58 | + show_button = flags.is_feature_enabled("secret_button") |
| 59 | + button_data = json.loads(flags.get_feature_value("secret_button")) |
| 60 | + |
| 61 | + return render_template( |
| 62 | + "home.html", show_button=show_button, button_colour=button_data["colour"] |
| 63 | + ) |
0 commit comments