def dotenv_get_set(key: str, default: Optional[str]) -> Optional[str]: # If env has key, use that value first, it overrides .env value = os.getenv(key, None) if value is not None: return value # find dot env file, make one in cwd if one doesn't exist dotenv_file = dotenv.find_dotenv() if dotenv_file == '': open('.env', 'w').close() dotenv_file = dotenv.find_dotenv() # Get the value from the .env, will be None if it doesn't exist value = dotenv.get_key(dotenv_file, key) # Treat empty values in .env as None if value == '': value = None # If value is not in .env set the default, will not use sys env if value is None: print(f'\tSetting default value for {key} to {default}') dotenv.set_key(dotenv_file, key, default or '', quote_mode='never') return default return value
def test_run(tmp_path): dotenv_file = tmp_path / '.env' dotenv_file.touch() sh.cd(str(tmp_path)) dotenv.set_key(str(dotenv_file), 'FOO', 'BAR') result = sh.dotenv('run', 'printenv', 'FOO').strip() assert result == 'BAR'
def tweet_generated_song(parts, number): load_dotenv(find_dotenv()) if not (os.environ.get('TWITTER_AUTH_TOKEN') or os.environ.get('TWITTER_AUTH_SECRET')): twitter = Twython(os.environ.get('TWITTER_CONSUMER_KEY'), os.environ.get('TWITTER_CONSUMER_SECRET')) auth = twitter.get_authentication_tokens() verifier = input( 'Please visit {} for authorizing your twitter and type the ' 'verification code here: '.format(auth['auth_url'])) twitter = Twython(os.environ.get('TWITTER_CONSUMER_KEY'), os.environ.get('TWITTER_CONSUMER_SECRET'), auth['oauth_token'], auth['oauth_token_secret']) final_step = twitter.get_authorized_tokens(verifier) set_key(find_dotenv(), 'TWITTER_AUTH_TOKEN', final_step['oauth_token']) set_key(find_dotenv(), 'TWITTER_AUTH_SECRET', final_step['oauth_token_secret']) load_dotenv(find_dotenv()) twitter = Twython(os.environ.get('TWITTER_CONSUMER_KEY'), os.environ.get('TWITTER_CONSUMER_SECRET'), os.environ.get('TWITTER_AUTH_TOKEN'), os.environ.get('TWITTER_AUTH_SECRET')) with open(path('out.mp4'), 'rb') as video: response = twitter.upload_video(media=video, media_type='video/mp4', media_category='tweet_video', check_progress=True) twitter.update_status(status=update_header( 'Musikalisches Würfelspiel (K516f) No. #id#', number, parts), media_ids=[response['media_id_string']])
def disable_auth(dotenv_filepath, affected_services, ui_container_name, service_details, root_user, base_dir): """ This function is to disable authentication in DLTK services :param affected_services: containers which needs to be restarted :param ui_container_name: container name of UI portal for user management :param service_details: container details :return: True, if process is successful """ # update auth in required .env files dotenv.load_dotenv(dotenv_filepath) dotenv.set_key(dotenv_filepath, "AUTH_ENABLED", 'false') # stop all necessary containers # stop containers for service in affected_services: container_names = service_details[service].get('container_names', []) for container_name in container_names: if is_container_running(container_name): print(f"restarting container {container_name}") kill_container(container_name) # uninstall UI container - both image & container uninstall_container(ui_container_name) # Start required services for service in affected_services: if service != ui_container_name: install_service(service, service_details, root_user, base_dir) return True
def enable_auth(dotenv_filepath, affected_services, service_details, root_user, base_dir): """ This function is to enable authentication :param dotenv_filepath: file path of solution service :param affected_services: containers which needs to be restarted :param service_details: Container details :return: True if process successful """ # update auth in required .env files dotenv.load_dotenv(dotenv_filepath) dotenv.set_key(dotenv_filepath, "AUTH_ENABLED", 'true') # Restart registry, base, kong # stop containers for service in affected_services: container_names = service_details[service].get('container_names', []) for container_name in container_names: if is_container_running(container_name): print(f"restarting container {container_name}") kill_container(container_name) # start containers for service in affected_services: install_service(service, service_details, root_user, base_dir) print("restarted container") return True
async def on_message(message): settings = 'settings.env' dotenv.load_dotenv(settings) corruption = int(dotenv.get_key(settings, 'CORRUPTION')) stat_pc = corruption / 10 stat_rep = 'Memory fragmentation at ' + str(stat_pc) + '%' #don't let the bot reply to itself if message.author == client.user: return if corruption > 1000: fact_file = 'glitch.txt' dotenv.set_key(settings, 'CORRUPTION', str(0)) else: fact_file = 'facts.txt' corruption += random.randint(1, 20) dotenv.set_key(settings, 'CORRUPTION', str(corruption)) with open(fact_file, 'r') as facts: list_facts = facts.readlines() rng_fact = random.choice(list_facts) state_fact = 'Fact: ' + rng_fact if message.content.startswith('&fact'): await message.channel.send(state_fact) if message.content.startswith('&status'): await message.channel.send(stat_rep)
def init_page(page_name): """ Create a new page inside a new directory, containing boiler-plate for react Also adds the page directory to NODE_PATH in .env """ check_cache() page_dir = Path.cwd() / page_name print('{} {}…'.format( white('Creating new page', bold=True), green(page_name, bold=True), )) try: shutil.copytree(CACHE_DIR / 'src', page_dir) except FileExistsError: print(red('Error: Directory already exists!')) else: print(blue(f'Copied page boilerplate to {page_dir}')) # update .env dotenv_path = Path.cwd() / '.env' if dotenv_path.exists(): node_path = dotenv.get_key(str(dotenv_path), 'NODE_PATH') or "." page_node_path = os.path.relpath(page_dir, dotenv_path.parent) if page_node_path not in node_path.split(os.pathsep): node_path += os.pathsep + page_node_path dotenv.set_key(str(dotenv_path), 'NODE_PATH', node_path) print('{} {} {}'.format(white('Run', bold=True), magenta('react-pages develop', bold=True), white('to use this page.', bold=True)))
def refresh_access_token(): """ Refresh short access token """ dotenvfile = find_dotenv() load_dotenv(dotenvfile) with warnings.catch_warnings(record=True) as warns: warnings.simplefilter("ignore", ResourceWarning) dotenv.get_key(dotenvfile, "FB_LONG_ACCESS_TOKEN") warns = filter(lambda i: issubclass(i.category, UserWarning), warns) if warns: request_url = FB_URL + "oauth/access_token" request_payload = { "grant_type": "fb_exchange_token", "client_id": FB_APP_ID, "client_secret": FB_APP_SECRET, "fb_exchange_token": FB_SHORT_ACCESS_TOKEN, } response = REQ_SESSION.get(request_url, params=request_payload).json() dotenvfile = find_dotenv() load_dotenv(dotenvfile) print(response) dotenv.set_key(dotenvfile, "FB_LONG_ACCESS_TOKEN", response["access_token"]) PAYLOAD["access_token"] = dotenv.get_key(dotenvfile, "FB_LONG_ACCESS_TOKEN")
def _updatekey(self, soup, firstfile=True): # check the key tmpjs = str(soup.find("script", text=re.compile('base.js'))) basejs = tmpjs[tmpjs.index("jsUrl") + 8:tmpjs.index('base.js')] + "base.js" if os.getenv("BASEURL") == basejs and firstfile: print("--------------------the same jsdata---------------") else: # get the search page text = requests.get("https://www.youtube.com" + basejs).text print(basejs, "---------------------------") index = text.find('(decodeURIComponent(c))') firstkey = text[index - 2:index] result = re.search(firstkey + '=function' + "(.*?)};", text).group(1) firstfunc = "var " + firstkey + "=function" + result + "};" secondkey = re.search(r";(.*?)(\[|\.)", result).group(1) index = text.find("var " + secondkey) tmpline = text[index:index + 250] secondfunc = tmpline[:tmpline.find('};') + 1] file = open(self.decodecheck['path'], 'w', encoding="utf-8") os.environ["BASEKEY"] = firstkey set_key(find_dotenv(), "BASEKEY", os.environ["BASEKEY"]) os.environ["BASEURL"] = basejs set_key(find_dotenv(), "BASEURL", os.environ["BASEURL"]) file.write(firstfunc + "\n\n" + secondfunc) print("update key: " + firstkey + "---------" + secondkey) file.close()
def inject_filestash_config_path( osparc_simcore_scripts_dir: Path, monkeypatch_module: MonkeyPatch, env_file_for_testing: Path, ) -> None: create_filestash_config_py = ( osparc_simcore_scripts_dir / "filestash" / "create_config.py" ) # ensures .env at git_root_dir, which will be used as current directory assert env_file_for_testing.exists() env_values = dotenv_values(env_file_for_testing) process = subprocess.run( ["python3", f"{create_filestash_config_py}"], shell=False, check=True, stdout=subprocess.PIPE, env=env_values, ) filestash_config_json_path = Path(process.stdout.decode("utf-8").strip()) assert filestash_config_json_path.exists() set_key( env_file_for_testing, "TMP_PATH_TO_FILESTASH_CONFIG", f"{filestash_config_json_path}", ) monkeypatch_module.setenv( "TMP_PATH_TO_FILESTASH_CONFIG", f"{filestash_config_json_path}" )
def set_go_version(self, go_version: str, commit_message: str, source_branch_name: str) -> Optional[GitCommit]: """ Makes the commits necessary to change the Go version used by the repository. This includes updating the GO_VERSION and .env files at the repository's root. """ master_tip = self.repo.get_branch('master').commit sha = master_tip.sha ref = f'refs/heads/{source_branch_name}' self.repo.create_git_ref(ref, sha) print(f'Created branch {source_branch_name}') go_version_file = getenv(ENV_GO_VERSION_FILE) with open(go_version_file, 'w') as go_version_file_stream: go_version_file_stream.write(f'{go_version}\n') env_file = getenv(ENV_ENV_FILE) env_path = PurePath(os.path.dirname(env_file), ".env") set_key(dotenv_path=env_path, key_to_set=GO_VERSION_KEY, value_to_set=go_version, quote_mode='never') return self.update_files_on_tree( head=master_tip, files_to_check=[go_version_file, env_file], commit_message=commit_message, source_branch_name=source_branch_name)
def update_env(env_path, key='', value='', password='', keyfile=''): """Update a value in an encrypted .env file. This will encrypt the new value using the password or keyfile. Args: env_path (string): Path to the .env file to load. key (string): Name of the key to update. value (string): Updated value to set to the key. password (string): Password used to encrypt the .env file. keyfile (string): File used to encrypt the .env file. Example: >>> import os >>> from env_crypt import load_env >>> update_env('test.env', key='key', value='new value', password='******') """ if key is None or value is None: raise ValueError("You must specify a key and a value" " to update the env file.") salt = dotenv.get_key(env_path, 'salt') enc_key, _ = get_enc_key(password, keyfile, salt=salt) enc_value = encrypt_string(value, enc_key) dotenv.set_key(env_path, key, enc_value) return
def env_setup(): """Helper function to setup connection with Project Bonsai Returns ------- Tuple workspace, and access_key """ load_dotenv(verbose=True) workspace = os.getenv("SIM_WORKSPACE") access_key = os.getenv("SIM_ACCESS_KEY") env_file_exists = os.path.exists(".env") if not env_file_exists: open(".env", "a").close() if not all([env_file_exists, workspace]): workspace = input("Please enter your workspace id: ") set_key(".env", "SIM_WORKSPACE", workspace) if not all([env_file_exists, access_key]): access_key = input("Please enter your access key: ") set_key(".env", "SIM_ACCESS_KEY", access_key) load_dotenv(verbose=True, override=True) workspace = os.getenv("SIM_WORKSPACE") access_key = os.getenv("SIM_ACCESS_KEY") return workspace, access_key
def override_default_config(override_config_file_path): print(f"updating config from {override_config_file_path}") override_config = dotenv_values(override_config_file_path) print(colored("Overriding default config", "green")) for env_path in Path('').rglob('*.env'): env_config = dotenv_values(env_path) for key, value in override_config.items(): if key in env_config: if env_config[key] != value: print( f"updating {colored(key,'yellow')}:{colored(env_config[key],'green')} to {colored(key, 'yellow')}:{colored(value,'green')} in {env_path}" ) set_key(env_path, key, value) sys_name = os.name if sys_name == 'posix' or sys_name == 'mac': os.system( f"sudo chown -R $USER:$USER {os.path.dirname(os.path.abspath(__file__))}" ) # Note: Update GCS json file gcs_file_path = override_config.get('GCP_SERVICE_ACCOUNT_FILE_PATH', None) dst_gcs_file_path = "base/solution-config/dltk-ai.json" if gcs_file_path is not None and os.path.exists(gcs_file_path): shutil.copyfile(gcs_file_path, dst_gcs_file_path) return
def call_backend(self, other_args: List[str]): """Process backend command""" parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog="backend", description="Backend to use for plotting", ) parser.add_argument( "-v", "--value", type=str, dest="value", help="value", ) if other_args and "-" not in other_args[0][0]: other_args.insert(0, "-v") ns_parser = parse_known_args_and_warn(parser, other_args) if ns_parser: dotenv.set_key(self.env_file, "GTFF_BACKEND", str(ns_parser.value)) if ns_parser.value == "None": cfg_plot.BACKEND = None # type: ignore else: cfg_plot.BACKEND = ns_parser.value console.print("")
def before_request(): if not os.environ.has_key('HEROKU_URL'): os.environ['HEROKU_URL'] = request.headers['HOST'] dotenv.set_key(env_file, 'HEROKU_URL', os.environ['HEROKU_URL']) t = threading.Thread(target=ping_me) t.start() return
def load_env(self): print("Loading up environment variables:") dotenv_file = find_dotenv() load_dotenv(dotenv_file) os.environ["DATE"] = time.strftime("%B %d, %Y at %H:%M") set_key(dotenv_file, "DATE", os.environ["DATE"])
def admin_config(): form = ConfigForm() # 从配置config全局对象读取数据内容到表中 config_name_list = [i for i in dir(form) if i.isupper()] env = os.environ.get('FLASK_BMS_ENV') or 'default' env_path = getattr(config[env],'ENV_PATH') if form.validate_on_submit(): for c in config_name_list: data = ConfigTable.query.filter_by(name=c).first() if data is None: data = ConfigTable(name=c,config_value=str(form[c].data),type_name=type(form[c].data).__name__) else: data.name=c data.config_value = str(form[c].data) data.type_name = type(form[c].data).__name__ db.session.add(data) set_key(env_path,c,form[c].data) setattr(config[env],c,form[c].data) # 保存数据库 db.session.commit() return redirect(url_for('admin.admin_config')) else: # 从配置config全局对象读取数据内容到表中 config_name_list = [i for i in dir(form) if i.isupper()] env = os.getenv('FLASK_BMS_ENV') or 'default' for c in config_name_list: form[c].data = getattr(config[env],c) return custom_render_template('admin/config.html',form=form,app_name='Flask-BMS')
def main(): """Shows basic usage of the Docs API. Prints the title of a sample document. """ creds = auth() service = build('docs', 'v1', credentials=creds) # The ID of a sample document. DOCUMENT_ID = os.getenv("DOCUMENT_ID") # Retrieve the documents contents from the Docs service. if not DOCUMENT_ID: title = 'Internal Monologue' body = { 'title': title } doc = service.documents().create(body=body).execute() print('Created document with title: {0}'.format(doc.get('title'))) if not os.path.exists(".env"): os.write(".env") DOCUMENT_ID = doc.get("documentId") set_key(".env", "DOCUMENT_ID", DOCUMENT_ID) document = service.documents().get(documentId=DOCUMENT_ID).execute() print('The title of the document is: {}'.format(document.get('title')))
def test_env(self, project, tap, session, plugin_invoker_factory): project.dotenv.touch() dotenv.set_key(project.dotenv, "DUMMY_ENV_VAR", "from_dotenv") dotenv.set_key(project.dotenv, "TAP_MOCK_TEST", "from_dotenv") subject = plugin_invoker_factory(tap) with subject.prepared(session): env = subject.env() # .env assert env["DUMMY_ENV_VAR"] == "from_dotenv" # Project env assert env["MELTANO_PROJECT_ROOT"] == str(project.root) # Project settings assert env["MELTANO_CLI_LOG_LEVEL"] == "info" # Plugin info assert env["MELTANO_EXTRACTOR_NAME"] == tap.name # Plugin settings assert env["MELTANO_EXTRACT_TEST"] == env[ "TAP_MOCK_TEST"] == "from_dotenv" assert env["MELTANO_EXTRACT__SELECT"] == env[ "TAP_MOCK__SELECT"] == '["*.*"]' # Plugin execution environment venv = VirtualEnv(project.venvs_dir(tap.type, tap.name)) assert env["VIRTUAL_ENV"] == str(venv.root) assert env["PATH"].startswith(str(venv.bin_dir)) assert "PYTHONPATH" not in env
def test_run(cli): with cli.isolated_filesystem(): sh.touch(dotenv_path) sh.cd(here) dotenv.set_key(dotenv_path, 'FOO', 'BAR') result = sh.dotenv('run', 'printenv', 'FOO').strip() assert result == 'BAR'
def main(): default_path = os.path.join(os.path.dirname(__file__), '..', '.env') default_path = os.path.abspath(default_path) parser = argparse.ArgumentParser( description=''' Get OAuth tokens, using CONSUMER_KEY and CONSUMER_SECRET from env and writing the new ACCESS_TOKEN and ACCESS_TOKEN_SECRET back to it.''', epilog=''' If env does not exist, but env.asc does, it will be decrypted with gpg2 to provide CONSUMER_KEY and CONSUMER_SECRET. If env already exists and contains ACCESS_TOKEN/ACCESS_TOKEN_SECRET, they will be preserved.''') parser.add_argument('env', nargs='?', default=default_path, help='environment file to read and update ' '(default: {}'.format(default_path)) checkedshirt.add_arguments(parser) args = parser.parse_args() checkedshirt.init(args) try: with open(args.env, 'x') as env_f: asc = args.env + '.asc' log.info("Populating %s from %s", args.env, asc) subprocess.call(('gpg2', '--decrypt', asc), stdout=env_f) except FileExistsError: pass dotenv.load_dotenv(args.env) consumer_key = os.environ["CONSUMER_KEY"] consumer_secret = os.environ["CONSUMER_SECRET"] ks = ('ACCESS_TOKEN', 'ACCESS_TOKEN_SECRET') if all(k in os.environ for k in ks): log.info('%s already contains %s', args.env, ' & '.join(ks)) return auth = tweepy.OAuthHandler(consumer_key, consumer_secret) try: redirect_url = auth.get_authorization_url() except tweepy.TweepError: log.exception('Failed to get authorization URL') exit(1) print() print("Go to %s" % redirect_url) verifier = input('Verifier: ') print() try: access_token, access_token_secret = auth.get_access_token(verifier) dotenv.set_key(args.env, 'ACCESS_TOKEN', access_token) dotenv.set_key(args.env, 'ACCESS_TOKEN_SECRET', access_token_secret) except tweepy.TweepError: log.exception('Failed to get access token') exit(1)
def newKey(key, trycode, keymode, KEY): screen.text('Change', 1) # Beginning prompt if len(trycode) == 0: print('Input 4 digit code') # Read code change and apply change to global KEY (not global) elif len(trycode) == 4: # Backend set set_key('.env', 'KEY', trycode) # Apply change in front KEY = trycode screen.text(f'to {trycode}', 2) trycode = '' keymode = 'enter' # Show new code breifly sleep(1) screen.text('Attempt', 1) buzzer.beep(0.2, 0.1, n=3) # return values to change (no global var writing) return trycode, keymode, KEY
def on_status(self, mention): if mention.id > self.myLastRun: set_key(".env", "LAST_RUN", str(mention.id)) self.myLastRun = mention.id requestor = mention.author # User obj of requestor subjectAuthor_str = mention.in_reply_to_screen_name # Screen name of target tweet author subjectTweetId = mention.in_reply_to_status_id # Target tweet id print("tweet {}".format(subjectTweetId)) subjectTweet = self.api.get_status(subjectTweetId, include_entities=True, tweet_mode='extended', trim_user=True) conversationalists = "@{}".format(requestor.screen_name) if DEBUG: print(conversationalists) allMedia = subjectTweet.extended_entities.get('media', []) mediaFound = self.find_images( allMedia) ## Fixes #5, entities did not include all images chainTo = mention.id for task in mediaFound: if DEBUG: print(" {} OCR image {}".format(subjectTweetId, task)) result = self.ocr2tweets(task, conversationalists, chainTo) if DEBUG: print(" {} ".format(result))
def update_most_favorites(tweet): most_recent_count = int(tweet.favorite_count) most_count = int(os.environ['MOST_FAVORITES']) if most_recent_count > most_count: dotenv.set_key(dotenv.find_dotenv(), 'MOST_FAVORITES', str(most_recent_count)) return True return False
def dump(filename: str, variables: Dict[str, str], overwrite: bool) -> None: """Sets `variables` to the file at `filename`.""" if overwrite: with open(filename, mode="w"): pass for key, value in variables.items(): set_key(filename, key, value, quote_mode="never") # type: ignore
def set_last_user_id(df): """Set the value of LAST_USER_ID in our .env file to be the highest id we imported today. Args: df: Dataframe of users that were imported to mailchimp.""" last_id = str(df['id'].max()) print(f"Users added through {last_id}") set_key(".env", "LAST_USER_ID", last_id)
def decrypt_env(env_path, password='', keyfile=''): enc_key = get_key(password, keyfile) values = dotenv.main.dotenv_values(env_path) for key, value in values.items(): dec_value = decrypt_string(value, enc_key) dotenv.set_key(env_path, key, dec_value) return
def handle(self, *args, **options): API_KEY = input("Enter API KEY: ") API_SECRET = input("Enter API SECRET: ") with open('.env', 'w') as fp: fp.write('') dotenv.set_key(dotenv.find_dotenv(), 'API_KEY', API_KEY) dotenv.set_key(dotenv.find_dotenv(), 'API_SECRET', API_SECRET) self.stdout.write(self.style.SUCCESS('Successfully created .env file'))
def test_set_key(dotenv_file): success, key_to_set, value_to_set = dotenv.set_key(dotenv_path, 'HELLO', 'WORLD') success, key_to_set, value_to_set = dotenv.set_key(dotenv_path, 'foo', 'bar') dotenv.get_key(dotenv_path, 'HELLO') == 'WORLD' success, key_to_set, value_to_set = dotenv.set_key(dotenv_path, 'HELLO', 'WORLD 2') dotenv.get_key(dotenv_path, 'HELLO') == 'WORLD 2' dotenv.get_key(dotenv_path, 'foo') == 'bar'
def test_get_key(dotenv_file): success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, 'HELLO', 'WORLD') stored_value = dotenv.get_key(dotenv_file, 'HELLO') assert stored_value == 'WORLD' sh.rm(dotenv_file) assert dotenv.get_key(dotenv_file, 'HELLO') is None success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, 'HELLO', 'WORLD') assert success is None
def setenv(key, value, dotenv_path=None): # pragma: no cover if dotenv_path is None: dotenv_path = Path('.env').resolve() opts = ctx_opts() if opts.dry_run or opts.verbose: click.secho(f'{const.LOG_ENV} {key}={value}', fg='magenta', color=opts.color) if not opts.dry_run: dotenv.set_key(dotenv_path, key, value, quote_mode='never')
def test_get_key(): sh.touch(dotenv_path) success, key_to_set, value_to_set = dotenv.set_key(dotenv_path, 'HELLO', 'WORLD') stored_value = dotenv.get_key(dotenv_path, 'HELLO') assert stored_value == 'WORLD' sh.rm(dotenv_path) assert dotenv.get_key(dotenv_path, 'HELLO') is None success, key_to_set, value_to_set = dotenv.set_key(dotenv_path, 'HELLO', 'WORLD') assert success is None
def test_set_key_permission_error(dotenv_file): os.chmod(dotenv_file, 0o000) with pytest.raises(Exception): dotenv.set_key(dotenv_file, "HELLO", "WORLD") os.chmod(dotenv_file, 0o600) with open(dotenv_file, "r") as fp: assert fp.read() == ""
def test_load_dotenv(tmp_path): os.chdir(str(tmp_path)) dotenv_path = '.test_load_dotenv' sh.touch(dotenv_path) set_key(dotenv_path, 'DOTENV', 'WORKS') assert 'DOTENV' not in os.environ success = load_dotenv(dotenv_path) assert success assert 'DOTENV' in os.environ assert os.environ['DOTENV'] == 'WORKS'
def test_get_key_with_interpolation_of_unset_variable(dotenv_file): dotenv.set_key(dotenv_file, 'FOO', '${NOT_SET}') # test unavailable replacement returns empty string stored_value = dotenv.get_key(dotenv_file, 'FOO') assert stored_value == '' # unless present in environment os.environ['NOT_SET'] = 'BAR' stored_value = dotenv.get_key(dotenv_file, 'FOO') assert stored_value == 'BAR' del(os.environ['NOT_SET'])
def test_load_dotenv_override(tmp_path): os.chdir(str(tmp_path)) dotenv_path = '.test_load_dotenv_override' key_name = "DOTENV_OVER" sh.touch(dotenv_path) os.environ[key_name] = "OVERRIDE" set_key(dotenv_path, key_name, 'WORKS') success = load_dotenv(dotenv_path, override=True) assert success assert key_name in os.environ assert os.environ[key_name] == 'WORKS'
def test_unset_cli(cli, dotenv_file): success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, 'TESTHELLO', 'WORLD') dotenv.get_key(dotenv_file, 'TESTHELLO') == 'WORLD' result = cli.invoke(dotenv_cli, ['--file', dotenv_file, 'unset', 'TESTHELLO']) assert result.exit_code == 0, result.output assert result.output == 'Successfully removed TESTHELLO\n' dotenv.get_key(dotenv_file, 'TESTHELLO') is None result = cli.invoke(dotenv_cli, ['--file', dotenv_file, 'unset', 'TESTHELLO']) assert result.exit_code == 1, result.output
def test_set_key(dotenv_file): success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, 'HELLO', 'WORLD') success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, 'foo', 'bar') assert dotenv.get_key(dotenv_file, 'HELLO') == 'WORLD' with open(dotenv_file, 'r') as fp: assert 'HELLO="WORLD"\nfoo="bar"' == fp.read().strip() success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, 'HELLO', 'WORLD 2') assert dotenv.get_key(dotenv_file, 'HELLO') == 'WORLD 2' assert dotenv.get_key(dotenv_file, 'foo') == 'bar' with open(dotenv_file, 'r') as fp: assert 'HELLO="WORLD 2"\nfoo="bar"' == fp.read().strip() success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, "HELLO", "WORLD\n3") with open(dotenv_file, "r") as fp: assert 'HELLO="WORLD\n3"\nfoo="bar"' == fp.read().strip()
def release_superset(ctx, version): # TODO: make variable project = ctx['project_name'] project_root = f'../{project}' bucket_name = ctx['S3_BUCKET_NAME'] do(ctx, 'rm -rf superset/assets/dist/*') do(ctx, 'yarn run build', path='superset/assets/') do(ctx, 'rm -rf build/*') do(ctx, 'python setup.py bdist_wheel') do(ctx, f'aws s3 cp --quiet dist/superset-{version}-py3-none-any.whl s3://{bucket_name}/superset/dist/') do(ctx, f'cp ./dist/superset-{version}-py3-none-any.whl {project_root}/tests/stack/superset/') # TODO: wrap set_key in function if not env.dry_run: # dotenv -f .env -q auto set VERSION version set_key( dotenv_path=f'{project_root}/.env', key_to_set='SUPERSET_VERSION', value_to_set=version, quote_mode='auto') else: print(REMOTE_PREFIX if ctx.get('host', False) else LOCAL_PREFIX, f'dotenv -f {project_root}/.env -q auto set SUPERSET_VERSION {version}') compose(ctx, 'build superset', path=f'{project_root}')
def test_get_key_with_interpolation(dotenv_file): sh.touch(dotenv_file) dotenv.set_key(dotenv_file, 'HELLO', 'WORLD') dotenv.set_key(dotenv_file, 'FOO', '${HELLO}') dotenv.set_key(dotenv_file, 'BAR', 'CONCATENATED_${HELLO}_POSIX_VAR') with open(dotenv_file) as f: lines = f.readlines() assert lines == [ 'HELLO="WORLD"\n', 'FOO="${HELLO}"\n', 'BAR="CONCATENATED_${HELLO}_POSIX_VAR"\n', ] # test replace from variable in file stored_value = dotenv.get_key(dotenv_file, 'FOO') assert stored_value == 'WORLD' stored_value = dotenv.get_key(dotenv_file, 'BAR') assert stored_value == 'CONCATENATED_WORLD_POSIX_VAR' # test replace from environ taking precedence over file os.environ["HELLO"] = "TAKES_PRECEDENCE" stored_value = dotenv.get_key(dotenv_file, 'FOO') assert stored_value == "TAKES_PRECEDENCE"
def write_config(key, val): return dotenv.set_key(dotenv_path, key, val)
def get_valid_user(): user = random.choice(OPTED_IN_USERS) if user == get_env_variable('LAST_USER'): user = get_valid_user() set_key(os.path.join(BASE_DIR, '.env'), 'LAST_USER', user) return user
def test_list(cli, dotenv_file): success, key_to_set, value_to_set = dotenv.set_key(dotenv_file, 'HELLO', 'WORLD') result = cli.invoke(dotenv_cli, ['--file', dotenv_file, 'list']) assert result.exit_code == 0, result.output assert result.output == 'HELLO=WORLD\n'
def liff_init(access_token): if not dotenv.set_key(dotenv_path, LIFF_ACCESS_TOKEN_KEY, access_token): print("Cannot save the token to local")
def set_dotenv_key(key_to_set, value_to_set): set_key(dotenv_file_path, key_to_set, value_to_set)