I have this code for a function to populate a connection string for sqlalchemy
def sql_path(yaml_path=None, login_key='login', user_key='username',
pass_key='password', api_key=None, dialect=None,
driver=None, host='localhost', port=None, database=None):
with open(yaml_path, 'r') as file:
sql_yaml = yaml.load(file, Loader=yaml.FullLoader)
user = sql_yaml[login_key][user_key]
password = sql_yaml[login_key][pass_key]
pw_encoded = urllib.parse.quote_plus(password)
if api_key is not None:
if 'dialect' in sql_yaml[api_key].keys():
dialect = sql_yaml[api_key]['dialect']
if 'driver' in sql_yaml[api_key].keys():
driver = sql_yaml[api_key]['driver']
if 'host' in sql_yaml[api_key].keys():
host = sql_yaml[api_key]['host']
if 'port' in sql_yaml[api_key].keys():
port = sql_yaml[api_key]['port']
if 'database' in sql_yaml[api_key].keys():
database = sql_yaml[api_key]['database']
if port is None:
sql_path = f'{dialect}+{driver}://{user}:{pw_encoded}@{host}/{database}'
else:
sql_path = f'{dialect}+{driver}://{user}:{pw_encoded}@{host}:{port}/{database}'
return sql_path
Is there a way to dynamically assign the variables in the 'if api_key...' block without having to do an if statement for each of them?