def index(): theme = request.args.get("theme") if theme: updateTheme(theme) showWidgets = ldclient.get().variation('show-widgets', current_user.get_ld_user(), False) if showWidgets: display_widgets = True else: display_widgets = False ''' showWidgets = ld_client.variation("switch-feature", {'key': '*****@*****.**'}, False) if showWidgets == 'Red': display_widgets = 'Red' elif showWidgets == 'Blue': display_widgets = 'Blue' elif showWidgets == 'Green': display_widgets = 'Green' ''' all_flags = json.dumps(ldclient.get().all_flags(current_user.get_ld_user())) beta_features = ldclient.get().variation('dark-theme', current_user.get_ld_user(), False) set_theme = '{0}/index.html'.format(current_user.set_path) LD_FRONTEND_KEY = current_app.config["LD_FRONTEND_KEY"] return render_template(set_theme, title='Home', display_widgets=display_widgets, all_flags=all_flags, show_beta=beta_features, LD_FRONTEND_KEY=LD_FRONTEND_KEY)
def test_set_sdk_key_after_init(): ldclient.set_config(Config.default()) assert ldclient.get().is_initialized() is False ldclient.set_sdk_key(sdk_key) wait_until(ldclient.get().is_initialized, timeout=30) ldclient.get().close()
def test_set_sdk_key_before_init(): ldclient.set_config(Config.default()) ldclient.set_sdk_key(sdk_key) wait_until(ldclient.get().is_initialized, timeout=30) ldclient.get().close()
def test_set_config(): offline_config = ldclient.Config(offline=True) online_config = ldclient.Config(sdk_key=sdk_key, offline=False) ldclient.set_config(offline_config) assert ldclient.get().is_offline() is True ldclient.set_config(online_config) assert ldclient.get().is_offline() is False wait_until(ldclient.get().is_initialized, timeout=30) ldclient.get().close()
def get_ld_client(): #if this was an app in prod, keey would go in secret file #hard-coding as a shortcut for now! if "ld_client" not in g: ldclient.set_config(Config("sdk-6d5668a8-bca4-43e8-a4ed-aae8b501be6c")) g.ld_client = ldclient.get() return g.ld_client
def test_set_config(): _reset_client() with start_server() as stream_server: with stream_content(make_put_event()) as stream_handler: try: stream_server.for_path('/all', stream_handler) ldclient.set_config(Config(sdk_key, offline=True)) assert ldclient.get().is_offline() is True ldclient.set_config(Config(sdk_key, stream_uri = stream_server.uri, send_events = False)) assert ldclient.get().is_offline() is False wait_until(ldclient.get().is_initialized, timeout=10) r = stream_server.await_request() assert r.headers['Authorization'] == sdk_key finally: _reset_client()
def test_set_sdk_key(): old_sdk_key = "OLD_SDK_KEY" new_sdk_key = "NEW_SDK_KEY" old_config = Config(sdk_key=old_sdk_key, stream=False, offline=True) ldclient.set_config(old_config) old_client = ldclient.get() assert old_client.get_sdk_key() == old_sdk_key ldclient.set_sdk_key(new_sdk_key) new_client = ldclient.get() assert new_client.get_sdk_key() == new_sdk_key # illustrates bad behavior- assigning value of ldclient.get() means # the old_client didn't get updated when we called set_sdk_key() assert old_client.get_sdk_key() == old_sdk_key
def index(): theme = request.args.get("theme") if theme: updateTheme(theme) beta_features = ldclient.get().variation('dark-theme', current_user.get_ld_user(), False) set_theme = '{0}/index.html'.format(current_user.set_path) return render_template(set_theme, title='Home', show_beta=beta_features)
def flag(event, context): root = logging.getLogger() root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) ldclient.set_sdk_key(os.environ['SDKKEY']) user = { "key": "*****@*****.**", "firstName": "Jon", "lastName": "Doe", "custom": { "groups": "beta_testers" } } flag_hoisted = ldclient.get().variation("flag-hoisted", user, False) if flag_hoisted: flag_status = "Hoisted" else: flag_status = "Lowered" ldclient.get().close() body = { "message": flag_status } response = { "statusCode": 200, "body": json.dumps(body) } return response
def test_set_sdk_key_after_init(): _reset_client() with start_server() as stream_server: with stream_content(make_put_event()) as stream_handler: try: stream_server.for_path('/all', BasicResponse(401)) ldclient.set_config( Config(stream_uri=stream_server.uri, send_events=False)) assert ldclient.get().is_initialized() is False r = stream_server.await_request() assert r.headers['Authorization'] == '' stream_server.for_path('/all', stream_handler) ldclient.set_sdk_key(sdk_key) wait_until(ldclient.get().is_initialized, timeout=30) r = stream_server.await_request() assert r.headers['Authorization'] == sdk_key finally: _reset_client()
def main(): module = AnsibleModule(argument_spec=dict( sdk_key=dict( required=True, type="str", no_log=True, fallback=(env_fallback, ["LAUNCHDARKLY_SDK_KEY"]), ), flag_key=dict(type="str", required=True), user=dict(type="dict", required=True), start_wait=dict(type="int", default=5), )) if not HAS_LD: module.fail_json(msg=missing_required_lib("launchdarkly-server-sdk"), exception=LD_IMP_ERR) ldclient.set_sdk_key(module.params["sdk_key"]) ldclient.start_wait = 5 ld_client = ldclient.get() if not ld_client.is_initialized(): raise AnsibleError("Error: Not Connected to LaunchDarkly") show_feature = ld_client.variation_detail(module.params["flag_key"], module.params["user"], False) ld_client.flush() ff_type = type(show_feature.value).__name__ value = show_feature.value ld_client.close() if ff_type == "dict": ff_end_type = "json" elif ff_type == "unicode": ff_end_type = "string" elif ff_type == "int": ff_end_type = "number" elif ff_type == "bool": ff_end_type = "bool" module.exit_json( type=ff_end_type, value=show_feature.value, variation_index=show_feature.variation_index, reason=show_feature.reason, is_default_value=show_feature.is_default_value(), )
def experiments(): theme = request.args.get("theme") if theme: updateTheme(theme) set_theme = '{0}/exp.html'.format(current_user.set_path) random_user = current_user.get_random_ld_user() show_nps = ldclient.get().variation('show-nps-survery', random_user, False) return render_template(set_theme, title='Experiments', show_nps=show_nps, random_user=random_user)
def index(): form = TaskForm() if form.validate_on_submit(): Task.add_task(current_user, form) return redirect(request.referrer) if current_user.is_authenticated: ld_user = current_user.get_ld_user() else: ld_user = {"key": "anon", "anonymous": True} show_new_theme = ldclient.get().variation("show-new-theme", ld_user, False) if show_new_theme: return render_template("home.html", form=form) else: return render_template("coming_soon.html")
def canary_route(): customer_type = request.args.get('customer_type') if customer_type == 'internal_qa': user = { "key": "internal_testing", "custom": { "groups": "beta_testers" } } else: user = {"key": "random_visitor"} show_feature = ldclient.get().variation("internal-customers", user, False) client_feature = True if show_feature == 'qa_enabled' else False return render_template('user.html', show_feature=client_feature)
def setLoggingLevel(): """Set Logging Level Based on Feature Flag This uses LaunchDarkly to update the logging level dynamically. Before each request runs, we check the current logging level and it does not match, we update it to the new value. Logging levels are integer values based on the standard Logging library in python: https://docs.python.org/3/library/logging.html#logging-levels This is an operational feature flag. """ from flask import request logLevel = ldclient.get().variation("set-logging-level", getLdMachineUser(request), logging.INFO) app.logger.info("Log level is {0}".format(logLevel)) # set app app.logger.setLevel(logLevel) # set werkzeug logging.getLogger('werkzeug').setLevel(logLevel) # set root logging.getLogger().setLevel(logLevel)
'%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) if __name__ == "__main__": ldclient.set_sdk_key("sdk-3b6da147-d4a0-4fc9-89d3-28a69f806949") user = { "key": "Unique ID", "firstName": "Katrina", "lastName": "Sanzi", "custom": { "groups": "beta_testers" } } show_feature = ldclient.get().variation("new-search-bar", user, False) if show_feature: print("Showing your feature") else: print("Not showing your feature") while 1: show_feature = ldclient.get().variation("new-search-bar", user, False) if show_feature: print("Showing your feature") break else: print("Not showing your feature") time.sleep(5) ldclient.get().close()
import ldclient if __name__ == "__main__": ldclient.set_sdk_key("sdk-48a8550a-99ed-4633-81de-9ae1655799ca") user = { "key": "*****@*****.**", "firstName": "Bob", "lastName": "Loblaw", "custom": { "groups": "beta_testers" } } show_feature = ldclient.get().variation("pge-model-a", user, False) if show_feature: print("Showing your feature") else: print("Not showing your feature") show_feature2 = ldclient.get().variation("pge-model-b", user, False) if show_feature2: print("Showing your 2nd feature") else: print("Not showing your 2nd feature") show_feature3 = ldclient.get().variation("pge-multivar", user, 'maybe') if show_feature3 == 'yes': {print("YES!!!")}
def index(): import uwsgi # fails in flask print("Threads: ", uwsgi.opt.get('threads')) ldclient.set_config(Config(LD_SDK_KEY)) ld_client = ldclient.get() return "Hello world"
while sign.lower() not in lastNameMap: print("You typed something wrong!") sign = input("Please enter your astrological sign: ") dragLastName = lastNameMap[sign.lower()] # set user info user = { "key": uuid.uuid4(), "firstName": firstname, "custom": { "astroSign": sign } } # evaluate feature flag disable_lastname = ldclient.get().variation("dg-first-name-only", user, False) if disable_lastname: print("Your Drag First Name is: ", dragFirstName) else: print("Your Drag Name is: ", dragFirstName, " ", dragLastName) # check if they want to play again playagain = input( "Would you like to generate another drag name? Enter " "Yes" " or " "No" ": ") while playagain.lower() != "yes" and playagain.lower() != "no": print("You typed something wrong!")
# get inputs from user firstname = input("Please enter your first name: ") lastname = input("Please enter your last name: ") emailaddr = input("Please enter your email address: ") # create the user key make_key() key = make_key() # user data to pass through, note IP info for targeting user = { "key": key, "firstName": firstname, "lastName": lastname, "email": emailaddr, "ip": ip_addr } # get variations, using walkthrough as basis. "test" is feature flag key show_feature = ldclient.get().variation("test", user, False) # if/else statement displays based on user targeting in dashboard if show_feature: print("Thank you, " + firstname + " " + lastname + ", your IP is allowed. You should visit " + site) else: print("Sorry, your IP is not allowed, as you can see here: " + siteoff) # close ld ldclient.get().close()
root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) if __name__ == "__main__": sdk_key = "YOUR_SDK_KEY" ldclient.set_config(Config(sdk_key)) user = { "key": "*****@*****.**", "firstName": "Bob", "lastName": "Loblaw", "custom": { "groups": "beta_testers" } } show_feature = ldclient.get().variation("YOUR_FLAG_KEY", user, False) if show_feature: print("Showing your feature") else: print("Not showing your feature") ldclient.get().close( ) # close the client before exiting the program - ensures that all events are delivered
def __call__(self): return ldclient.get().variation('disable-caching', getLdMachineUser(), True)
from flask_login import LoginManager from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from app.config import config from app.util import getLdMachineUser from app.cli import deploy_command db = SQLAlchemy() migrate = Migrate() bootstrap = Bootstrap() login = LoginManager() cache = Cache(config={'CACHE_TYPE': 'redis'}) # Operational Feature Flags CACHE_TIMEOUT = lambda : ldclient.get().variation('cache-timeout', getLdMachineUser(), 50) class CachingDisabled: def __call__(self): return ldclient.get().variation('disable-caching', getLdMachineUser(), True) def create_app(config_name): """Flask application factory. :param config_name: Flask Configuration :type config_name: app.config class :returns: a flask application """ app = Flask(__name__)
root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) if __name__ == "__main__": ldclient.set_sdk_key("SET-SDK-KEY") user = { "key": "*****@*****.**", "firstName": "Bob", "lastName": "Loblaw", "custom": { "groups": "beta_testers", "location": "NZ" } } show_feature = ldclient.get().variation("tali-hello-flag", user, False) if show_feature: print("Showing your feature") else: print("Not showing your feature") ldclient.get().close( ) # close the client before exiting the program - ensures that all events are delivered
import config import logging import ldclient print("This is a quick primer on LaunchDarkly. Hello LD") #import key & create the client ldclient.set_sdk_key(config.api_key) ld_client = ldclient.get() #create the user user = { "key": "UNIQUE IDENTIFIER", "firstName": "Rod", "lastName": "Clemente", } #grab show_feature states show_feature1 = ldclient.get().variation("first-flag", user, False) show_feature2 = ldclient.get().variation("second-flag", user, False) if show_feature1: print ("Lucky you! Feature 1 is showing") else: print ("Sorry to say, we aren't showing feature 1 right now") if show_feature2:
#simple Python3 code to demonstrate the use of LaunchDarkly feature flags #import the LaunchDarkly client import ldclient from ldclient.config import Config #create instance of LaunchDarkly client using Test Env key ldclient.set_config(Config("sdk-1c869509-b2b1-47d6-8fa2-827e08db955f")) ld_client = ldclient.get() #set value of user - in a dynamic execution this would be set on the fly user = { "key": "UNIQUE IDENTIFIER", "firstName": "Bob", "lastName": "Loblaw", "custom": { "groups": "beta_testers" } } #set the feature flag value (t/F) based on the flag ID and user name. show_feature = ld_client.variation("use-simple-average",user, False) # Score Calculating Function # using the "use-simple-average" feature flag to determine the algo def compute_score(r1,r2,r3): if show_feature: return (r1 + r2 + r3) / 3
import logging import sys import ldclient root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter( '%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) if __name__ == '__main__': ldclient.start_wait = 10 ldclient.set_sdk_key('YOUR_SDK_KEY') user = {u'key': 'userKey'} print(ldclient.get().variation("update-app", user, False)) ldclient.get().close()
from app import app from flask import render_template import ldclient ldclient.set_sdk_key("sdk-cf80f41f-438e-4e5b-8e12-c275e46e1338") ld_client = ldclient.get() user = {"key": "*****@*****.**"} @app.route('/') def app(): show_feature = ld_client.variation("new-flag", user, False) if show_feature: return render_template('sidebar.html') else: return render_template('base.html') # the code to run if the feature is off
def client(self): if self._client is None: self._client = ldclient.get() return self._client
'FEATURE_FLAGS_FILE=my_flags.yml') package_name = 'label_studio' if settings.VERSION_EDITION == 'Community Edition' else 'label_studio_enterprise' if settings.FEATURE_FLAGS_FILE.startswith('/'): feature_flags_file = settings.FEATURE_FLAGS_FILE else: feature_flags_file = find_node(package_name, settings.FEATURE_FLAGS_FILE, 'file') logger.info(f'Read flags from file {feature_flags_file}') data_source = Files.new_data_source(paths=[feature_flags_file]) config = Config(sdk_key=settings.FEATURE_FLAGS_API_KEY or 'whatever', update_processor_class=data_source, send_events=False) ldclient.set_config(config) client = ldclient.get() elif settings.FEATURE_FLAGS_OFFLINE: # On-prem usage, without feature flags file ldclient.set_config( Config(settings.FEATURE_FLAGS_API_KEY or 'whatever', offline=True)) client = ldclient.get() else: # Production usage if hasattr(settings, 'REDIS_LOCATION'): logger.debug( f'Set LaunchDarkly config with Redis feature store at {settings.REDIS_LOCATION}' ) store = Redis.new_feature_store(url=settings.REDIS_LOCATION, prefix='feature-flags', caching=CacheConfig(expiration=30)) ldclient.set_config(
import logging import sys import ldclient root = logging.getLogger() root.setLevel(logging.DEBUG) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) if __name__ == '__main__': ldclient.start_wait = 10 ldclient.set_sdk_key('YOUR_SDK_KEY') user = {u'key': 'userKey'} print(ldclient.get().variation("update-app", user, False)) ldclient.get().close()