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 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_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_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_unset(): 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' success, key_to_unset = dotenv.unset_key(dotenv_path, 'HELLO') assert dotenv.get_key(dotenv_path, 'HELLO') is None sh.rm(dotenv_path) success, key_to_unset = dotenv.unset_key(dotenv_path, 'HELLO') assert success is None
def tweepy_auth(): at = get_key( find_dotenv(), 'TWITTER-ACCESS-TOKEN' ) ats = get_key( find_dotenv(), 'TWITTER-ACCESS-TOKEN-SECRET' ) ck = get_key( find_dotenv(), 'TWITTER-CONSUMER-KEY' ) cs = get_key( find_dotenv(), 'TWITTER-CONSUMER-SECRET' ) auth = tweepy.OAuthHandler(ck, cs) auth.set_access_token(at, ats) api = tweepy.API(auth) return api
def requestHandler(request: pituophis.Request): # IF CLIENT IS CONNECTED if "/connected/" in request.path: print(request.path) user : User = userCache.pop(request.path.split("/")[2]) userCache[user.id] = user return ConnectedRoutes(request, userCache, user.id) # IF CLIENT NOT CONNECTED else: return UnconnectedRoutes(request, userCache) dotenv.get_key(".","HOST")
def test_get_key_with_interpolation_of_unset_variable(cli): with cli.isolated_filesystem(): sh.touch(dotenv_path) dotenv.set_key(dotenv_path, 'FOO', '${NOT_SET}') # test unavailable replacement returns empty string stored_value = dotenv.get_key(dotenv_path, 'FOO') assert stored_value == '' # unless present in environment os.environ['NOT_SET'] = 'BAR' stored_value = dotenv.get_key(dotenv_path, 'FOO') assert stored_value == 'BAR' del (os.environ['NOT_SET']) sh.rm(dotenv_path)
def _login(self): """get the username and password from dotenv file and logs into zabbix server and then sets the auth key in the payload.""" self.payload['method'] = 'user.login' self.payload['params'] = { 'user': dotenv.get_key(self.path, "zabbix_username"), 'password': dotenv.get_key(self.path, "zabbix_password") } self.payload['id'] = self.counter # print(self.payload) response = requests.post(URL, json=self.payload).json() self.payload['auth'] = response['result']
def meow(): # get the ip from dotenv file in code/.env ip = dotenv.get_key("code/.env", "ip") # get the hostname from dotenv file in code/.env hostname = dotenv.get_key("code/.env", "hostname") # lets check if we were successful to get the keys from code/.env if ip is None: exit() if hostname is None: exit() # lookup code/host.py about how to use this class. # lets try to add/remove/... to the zabbix-server mongo = Host(ip, hostname) print(mongo.payload)
def form_submit(): if request.method == 'POST': user_v = request.form['email'] passwd_v = request.form['password'] case_v = request.form['caseNumber'] attachment_type_v = request.form['attachment_type'] print(attachment_type_v) token_v = get_sfdc_token() storage_v = get_key(find_dotenv(),"Local_Dropbox_Folder") # check the case number is valid case_v = check_case_number(case_v) try: len(case_v) except: error = "Invalid case number" return render_template('index-error.html', error = error, token = token_v) # check SFDC credentials are valid salesforce_check = sfdc_authorization(user_v, passwd_v, token_v) if salesforce_check == 1: pass else: error = "Failed to connect to SFDC" return render_template('index-error.html', error = error, token = token_v) new_dir = "{}\\\\{}".format(storage_v, case_v) dropbox_baseURL = get_key(find_dotenv(),"Dropbox_URL") dropbox_URL = "{}/{}".format(dropbox_baseURL,case_v) download_attachments_on_case(user_v, passwd_v, case_v, token_v, storage_v, new_dir) if attachment_type_v == 'All File Types': download_attachments_all(user_v, passwd_v, case_v, token_v, storage_v, new_dir) else: download_attachment_email(user_v, passwd_v, case_v, token_v, storage_v, new_dir) file_length = cleanup(new_dir) if file_length > 0: return render_template("result.html", caseNumber = case_v, new_dir = dropbox_URL, files = file_length, token = token_v) else: error = "No photos to upload" return render_template('index-error.html', error = error, token = token_v)
def get_input_from_aoc(year: int, day: int) -> io.StringIO: session_id = dotenv.get_key(".env", "SESSION_ID") response = requests.get( f"https://adventofcode.com/{year}/day/{day}/input", cookies={"session": session_id}, ) return io.StringIO(response.text, newline="\n")
def selector(title: str, selectorId: str, userId: str, data: List[SelectorData], userCache: ExpiringDict, request: pituophis.Request) -> pituophisPage: if selectorId not in userCache[userId].selectors: userCache[userId].selectors[selectorId] = [] response: pituophisPage = [ pituophis.Item("i", title), ] for d in data: print(d.value, userCache[userId].selectors[selectorId]) entry: pituophis.Item = pituophis.Item( "1", "[{}] {}".format( 'X' if (d.value in userCache[userId].selectors[selectorId]) else ' ', d.name), "{}/{}/{}/{}".format(request.path, selectorId, d.value, str(random.randrange(0, 0xFFFF))), dotenv.get_key("../", "HOST"), 70) response += [entry] response += [pituophis.Item("i", "")] return response
def list_env(env_path, password='', keyfile=''): """Decrypt and list the values in the .env file. Args: env_path (string): Path to the .env file to load. 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 list_env >>> load_env('test.env', password='******') key1=value1 key2=value2 etc... """ salt = dotenv.get_key(env_path, 'salt') enc_key, _ = get_enc_key(password, keyfile, salt=salt) values = dotenv.main.dotenv_values(env_path) for key, value in values.items(): if key != 'salt': dec_value = decrypt_string(value, enc_key) else: dec_value = value print('%s="%s"' % (key, dec_value)) return
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 no_items(my_tags_list: list) -> bool: if len(my_tags_list) == 0: return messageBoxes.show_message_dialog( 'Critical', get_key(configTools.get_env_name(), 'NOTE_SETUP_EMPTY'), 'Внимание!') return False
def get_interval_info(): scan_interval = int( get_key(configTools.get_env_name(), 'SCAN_INTERVAL_MAX')) + 1 interval = configTools.get_interval() if interval not in range(1, scan_interval): interval = 3 return interval, scan_interval
def accept(self): current_rb = self.get_current_rb() if current_rb.objectName() == 'radioButton_not': current_option = '' else: current_option = self.rb_execute[current_rb.objectName()][2] # установить audio_dict = configTools.get_audio() new_audio_dict = { 'current': current_option, 'file': self.audioFile, 'beep': str(self.spinBox.value()), 'text': self.plainTextEdit.toPlainText(), } if new_audio_dict != audio_dict: messageBoxes.show_message_box( 'Information', get_key('my_env.env', 'NOTE_SAVE_SOUND_PARAM'), 'Информация!') configTools.set_audio(new_audio_dict) if current_option != '': # параметры менялись - но если текущее не выставлено - ничего не сохраняем soundNotification.set_current_audio( current_option, self.rb_execute[current_rb.objectName()][1]) self.hide()
def start(): token_v = get_sfdc_token() print(get_key(find_dotenv(),"Local_Dropbox_Folder")) print(token_v) #attachment_type_v = request.form['attachment'] #print(attachment_type_v) return render_template('index.html', token = token_v)
def set_logs(name, file_name) -> logging: log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' logging.basicConfig\ (level=logging.DEBUG, filename='.\\logs\\app_tmp.log', filemode='w', format=log_format, datefmt='%d-%b-%y %H:%M:%S') logger = logging.getLogger(name) c_format = \ logging.Formatter(fmt=log_format, datefmt='%d-%m-%y %H:%M:%S') # log - debug level and higher debug_log = logging.FileHandler('.\\logs\\' + file_name + '.log') # log errors error_log = logging.FileHandler('.\\logs\\' + file_name + 'Error.log') if get_key('my_env.env', 'APP_PRODUCTION') == 'True': debug_log.setLevel(logging.ERROR) error_log.setLevel(logging.CRITICAL) else: debug_log.setLevel(logging.DEBUG) error_log.setLevel(logging.ERROR) debug_log.setFormatter(c_format) error_log.setFormatter(c_format) logger.addHandler(error_log) logger.addHandler(debug_log) return logger
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
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 create_container(): client = docker.from_env() print("Creating container...") GenerateDotEnv() db_name = dotenv.get_key(dotenv_file, "MONGODB_DATABASE") db_user = dotenv.get_key(dotenv_file, "MONGODB_USERNAME") db_pass = dotenv.get_key(dotenv_file, "MONGODB_PASSWORD") container = client.containers.run("bitnami/mongodb", name="thgdb-mongodb", environment={ "MONGODB_DATABASE": db_name, "MONGODB_USERNAME": db_user, "MONGODB_PASSWORD": db_pass }, ports={'27017/tcp': 27017}, detach=True) return container
def default_headers(): access_token = dotenv.get_key(dotenv_path, LIFF_ACCESS_TOKEN_KEY) if access_token == None: print("please call liff.py init first <accessToken>") sys.exit() headers = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"} return headers
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()
def test_get_key_not_found(dotenv_file): logger = logging.getLogger("dotenv.main") with mock.patch.object(logger, "warning") as mock_warning: result = dotenv.get_key(dotenv_file, "foo") assert result is None mock_warning.assert_called_once_with("Key %s not found in %s.", "foo", dotenv_file)
def test_get_key_with_interpolation(cli): with cli.isolated_filesystem(): sh.touch(dotenv_path) dotenv.set_key(dotenv_path, 'HELLO', 'WORLD') dotenv.set_key(dotenv_path, 'FOO', '${HELLO}') dotenv.set_key(dotenv_path, 'BAR', 'CONCATENATED_${HELLO}_POSIX_VAR') # test replace from variable in file stored_value = dotenv.get_key(dotenv_path, 'FOO') assert stored_value == 'WORLD' stored_value = dotenv.get_key(dotenv_path, 'BAR') assert stored_value == 'CONCATENATED_WORLD_POSIX_VAR' # test replace from environ taking precedence over file environ["HELLO"] = "TAKES_PRECEDENCE" stored_value = dotenv.get_key(dotenv_path, 'FOO') assert stored_value == "TAKES_PRECEDENCE" sh.rm(dotenv_path)
def command_api_key_name(args): """ Get or set API_KEY_NAME """ if args.default: dotenv.set_key(DOT_ENV_PATH, key_to_set='API_KEY_NAME', value_to_set='access-token') if args.set: dotenv.set_key(DOT_ENV_PATH, key_to_set='API_KEY_NAME', value_to_set=args.set) print(dotenv.get_key(DOT_ENV_PATH, 'API_KEY_NAME'))
def command_api_key_domain(args): """ Get or set API_KEY_DOMAIN """ if args.default: dotenv.set_key(DOT_ENV_PATH, key_to_set='API_KEY_DOMAIN', value_to_set='localhost') if args.set: dotenv.set_key(DOT_ENV_PATH, key_to_set='API_KEY_DOMAIN', value_to_set=args.set) print(dotenv.get_key(DOT_ENV_PATH, 'API_KEY_DOMAIN'))
def get_env_value(key_to_get: str, env_file: str = ".dtransfer.prod.env") -> str: """ Load from general env then specific file if not found. Gets from OS.ENV as may be there when running locally and from envfile when running in docker. """ return os.getenv(key_to_get) or get_key(env_file, key_to_get)
def command_api_key_value(args): """ Get or set API_KEY_VALUE """ if args.generate: api_key = secrets.token_urlsafe(args.length) dotenv.set_key(DOT_ENV_PATH, key_to_set='API_KEY_VALUE', value_to_set=api_key) if args.set: dotenv.set_key(DOT_ENV_PATH, key_to_set='API_KEY_VALUE', value_to_set=args.set) print(dotenv.get_key(DOT_ENV_PATH, 'API_KEY_VALUE'))
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 test_get_key_ok(dotenv_file): logger = logging.getLogger("dotenv.main") with open(dotenv_file, "w") as f: f.write("foo=bar") with mock.patch.object(logger, "warning") as mock_warning: result = dotenv.get_key(dotenv_file, "foo") assert result == "bar" mock_warning.assert_not_called()
def connect_db(): try: client.containers.get("thgdb-mongodb").start() except: check() file_db_creds = dotenv_values(dotenv_file) dbcreds = {"MONGODB_DATABASE", "MONGODB_USERNAME", "MONGODB_PASSWORD"} if (file_db_creds == {} or not (file_db_creds.keys() >= dbcreds)): check() db_name = get_key(dotenv_file, "MONGODB_DATABASE") db_user = get_key(dotenv_file, "MONGODB_USERNAME") db_pass = get_key(dotenv_file, "MONGODB_PASSWORD") db = connect(db=db_name, username=db_user, password=db_pass, host='mongodb://' + db_user + ':' + db_pass + '@localhost/' + db_name) return db
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 test_key_value_without_quotes(dotenv_file): with open(dotenv_file, 'w') as f: f.write("TEST = value \n") assert dotenv.get_key(dotenv_file, 'TEST') == "value"
def denv(envkey): return dotenv.get_key(path.join(path.dirname(__file__), '.env'), envkey)
def test_value_with_simple_quotes(dotenv_file): with open(dotenv_file, 'w') as f: f.write("TEST='two words'\n") assert dotenv.get_key(dotenv_file, 'TEST') == 'two words'
def test_value_with_double_quotes(dotenv_file): with open(dotenv_file, 'w') as f: f.write('TEST="two words"\n') assert dotenv.get_key(dotenv_file, 'TEST') == 'two words'
def denv(envkey): return dotenv.get_key(join(abspath(dirname(__file__)), '.env'), envkey)
def test_value_with_special_characters(dotenv_file): with open(dotenv_file, 'w') as f: f.write(r'TEST="}=&~{,(\5%{&;"') assert dotenv.get_key(dotenv_file, 'TEST') == r'}=&~{,(\5%{&;'
def test_key_value_without_quotes_with_spaces(dotenv_file): with open(dotenv_file, 'w') as f: f.write('TEST = " with spaces " \n') assert dotenv.get_key(dotenv_file, 'TEST') == " with spaces "
import sys import glob import time import dweepy import tweepy import datetime import sqlite3 import RPi.GPIO as GPIO from dotenv import load_dotenv, find_dotenv, get_key os.system('modprobe w1-gpio') os.system('modprobe w1-therm') #base_dir = '/sys/bus/w1/devices/' base_dir = get_key( find_dotenv(), 'PROBE-BASEDIR' ).lower() GPIO.setmode(GPIO.BCM) GPIO.setup(7,GPIO.IN, pull_up_down=GPIO.PUD_UP) last_temp = {} conn = None curs = None try: conn=sqlite3.connect('/home/pi/TempPi/temppi.db') curs = conn.cursor() except: print ("No Database") def read_temp_raw(device_file):
def test_value_with_new_lines(dotenv_file): with open(dotenv_file, 'w') as f: f.write('TEST="a\nb"') assert dotenv.get_key(dotenv_file, 'TEST') == "a\nb"
def test_empty_value(dotenv_file): with open(dotenv_file, "w") as f: f.write("TEST=") assert dotenv.get_key(dotenv_file, "TEST") == ""
def test_value_after_comment(dotenv_file): with open(dotenv_file, "w") as f: f.write("# comment\nTEST=a") assert dotenv.get_key(dotenv_file, "TEST") == "a"