Skip to content

Instantly share code, notes, and snippets.

@mrgarymartin
Created November 1, 2023 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgarymartin/f19688aab3099da718568931086d30e9 to your computer and use it in GitHub Desktop.
Save mrgarymartin/f19688aab3099da718568931086d30e9 to your computer and use it in GitHub Desktop.
In this example, the ConfigManager class is responsible for managing the application configuration. It checks if the AZURE_ENVIRONMENT environment variable is set to determine if the application is running in Azure. If it is, it initializes the Azure App Configuration client and fetches configuration settings from there. If not, it loads environ…
import os
from dotenv import load_dotenv
from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting
class ConfigManager:
def __init__(self):
# Load environment variables from .env file for local development
load_dotenv()
# Check if running in Azure environment
self.is_azure_env = os.environ.get('AZURE_ENVIRONMENT') is not None
if self.is_azure_env:
# If running in Azure, initialize Azure App Configuration client
self.app_config_client = AzureAppConfigurationClient.from_connection_string(os.environ['AZURE_APP_CONFIGURATION_CONNECTION_STRING'])
else:
# If running locally, load environment variables from .env file
load_dotenv()
def get_config(self, key):
if self.is_azure_env:
# If running in Azure, fetch configuration from Azure App Configuration
try:
config_setting = self.app_config_client.get_configuration_setting(key)
return config_setting.value
except Exception as e:
print(f"Error fetching configuration from Azure App Configuration: {str(e)}")
return None
else:
# If running locally, fetch configuration from environment variables
return os.environ.get(key)
# Usage example
if __name__ == "__main__":
config_manager = ConfigManager()
# Fetching configuration for 'EXAMPLE_SETTING'
example_setting = config_manager.get_config('EXAMPLE_SETTING')
if example_setting is not None:
print(f"EXAMPLE_SETTING: {example_setting}")
else:
print("EXAMPLE_SETTING not found.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment