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 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 test_set_sdk_key_before_init(): _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(stream_uri=stream_server.uri, send_events=False)) ldclient.set_sdk_key(sdk_key) wait_until(ldclient.get().is_initialized, timeout=10) r = stream_server.await_request() assert r.headers['Authorization'] == sdk_key finally: _reset_client()
class Config(object): """Base Config""" # VERSION refers to the latest git SHA1 VERSION = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode('utf-8').rstrip() SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess-this' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'postgresql://{0}:{0}@{1}/{0}'.format( 'supportService', 'localhost' ) SQLALCHEMY_TRACK_MODIFICATIONS = False LOG_TO_STDOUT = os.environ.get('LOG_TO_STDOUT') CACHE_REDIS_HOST = os.environ.get('REDIS_HOST') or 'cache' # LaunchDarkly Config # If $LD_RELAY_URL is set, client will be pointed to a relay instance. if "LD_RELAY_URL" in os.environ: config = LdConfig( sdk_key = os.environ.get("LD_CLIENT_KEY"), base_uri = os.environ.get("LD_RELAY_URL"), events_uri = os.environ.get("LD_RELAY_URL"), stream_uri = os.environ.get("LD_RELAY_URL") ) ldclient.set_config(config) else: ldclient.set_sdk_key(os.environ.get("LD_CLIENT_KEY")) LD_FRONTEND_KEY = os.environ.get("LD_FRONTEND_KEY") root = logging.getLogger() root.setLevel(logging.INFO) @staticmethod def init_app(app): pass
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 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
class Config: """Base Config class""" SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string' SQLALCHEMY_TRACK_MODIFICATIONS = False # Flask Security SECURITY_URL_PREFIX = "/auth" SECURITY_PASSWORD_HASH = "pbkdf2_sha512" SECURITY_PASSWORD_SALT = SECRET_KEY SECURITY_EMAIL_SENDER = "*****@*****.**" SECURITY_REGISTERABLE = True SECURITY_RECOVERABLE = True SECURITY_TRACKABLE = True SECURITY_CHANGEABLE = True # LaunchDarkly ldclient.set_sdk_key(os.environ.get("LD_SDK_KEY")) @staticmethod def init_app(app): pass
class Config(object): """Base Config""" VERSION = '1.0.2' SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess-this' SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \ 'postgresql://{0}:{0}@{1}/{0}'.format( 'supportService', 'localhost' ) SQLALCHEMY_TRACK_MODIFICATIONS = False LOG_TO_STDOUT = os.environ.get('LOG_TO_STDOUT') CACHE_REDIS_HOST = os.environ.get('REDIS_HOST') or 'cache' # LaunchDarkly ldclient.set_sdk_key(os.environ.get("LD_CLIENT_KEY")) LD_FRONTEND_KEY = os.environ.get("LD_FRONTEND_KEY") root = logging.getLogger() root.setLevel(logging.INFO) @staticmethod def init_app(app): pass
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()
import logging import sys import ldclient import time 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) 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")
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!!!")}
} 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) if __name__ == "__main__": # Use example logging https://github.com/launchdarkly/hello-python 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) # Log Flask to same handler root.addHandler(default_handler) # Setup LD Client ld_client_key = os.environ.get('LD_KEY') ldclient.set_sdk_key(ld_client_key) atexit.register(on_exit) # Starting Flask server app.run()
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:
def create_app(config: Type[Config] = Config, custom_injector: injector.Injector = None, injector_modules=None) -> Tuple[Flask, Api]: app = Flask(__name__) api = Api(app) app.config.from_object(config) ldclient.set_sdk_key(config.LAUNCH_DARKLY_KEY) """----------------- Dependencies -----------------""" app_logger = AppLogger(app_name=config.APP_NAME, env=config.ENV) """----------------- Middleware ---------------------""" # Before Request # Perform these functions in the declared order before every request. app.before_request_funcs = {None: [record_time_of_request, record_request_id]} # After Request # Perform this function after every request. app.after_request(record_access_log) """----------------- Bind Resources -----------------""" api.add_resource(Health, '/healthcheck') api.add_resource(Liveness, '/liveness') api.add_resource(Readiness, '/readiness', resource_class_kwargs={'config': app.config, 'app_logger': app_logger}) loader = Filesystem(Repository(config.MODEL_BASE_DIR)) model_info = ModelInfo( config.USE_CASE_ID, config.MODEL_ID, config.MODEL_VERSION_ID, config.TRAINING_ID ) app_logger.info(msg="Loading model from file..") model = loader.load_model(model_info) redis_repository = RedisRepository( config, app_logger ) api.add_resource( Predict, '/predict', resource_class_kwargs={ 'predict_service': PredictService( app_logger, model, redis_repository ), 'app_logger': app_logger } ) api.add_resource(Home, '/', resource_class_kwargs={ 'config': app.config, 'model_info': model.to_model_info(), }) add_error_handler(app) app_logger.info(msg="The factory initiated the app successfully") return app, api
import ldclient import pandas as pd from collections import OrderedDict import uuid #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) if __name__ == "__main__": ldclient.set_sdk_key("SDK KEY_Emily's Test Project - Test") # load dictionaries with name/sign data firstNameMap = { 'a': 'Amethyst', 'b': 'Bold', 'c': 'Curvy', 'd': 'Daring', 'e': 'Electric', 'f': 'Fatal', 'g': 'Grace', 'h': 'Horrendous', 'i': 'Ign', 'j': 'Jolly', 'k': 'Killer', 'l': 'Loud',
Process LaunchDarkly webhooks to trigger a CI build when a new environment is created. """ import os import json import logging import ldclient from circleci.api import Api logger = logging.getLogger() logger.setLevel(logging.INFO) circleci = Api(os.environ.get("CIRCLE_TOKEN")) # key for production environment ldclient.set_sdk_key(os.environ.get("LD_CLIENT_KEY")) client = ldclient.get() def trigger_deloy(): params = {'build_parameters[CIRCLE_JOB]': 'deploy'} circleci.trigger_build(username='******', project='SupportService', params=params) def handler(event, context): """ AWS Lambda Handler """
import click import click_log from circleci.api import Api from cli.generators import ConfigGenerator from cli.ld import LaunchDarklyApi from cli.aws.aws import AwsApi from cli.aws.ec2 import EC2Client # set up logging logger = logging.getLogger(__name__) click_log.basic_config(logger) # key for production environment ldclient.set_sdk_key(os.environ.get("LD_PROD_KEY")) client = ldclient.get() @click.group() @click_log.simple_verbosity_option(logger) def cli(): pass @click.command() def deploy_relay(): """Deploy LD Relay to LightSail.""" l = LaunchDarklyApi(os.environ.get('LD_API_KEY'), 'ldsolutions.tk') envs = l.getEnvironments('support-service') c = ConfigGenerator()
import logging import sys import ldclient 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) if __name__ == "__main__": ldclient.set_sdk_key("YOUR_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:
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
import logging import sys import ldclient 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) 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")
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()