Multi-language support for notification content with locale management and text translation capabilities. AppriseLocale provides comprehensive internationalization features for notifications across different languages and regions.
Manages localization and language settings for notifications with support for multiple languages and regions.
class AppriseLocale:
def __init__(self, language=None):
"""
Initialize locale manager.
Parameters:
- language (str, optional): Language code (e.g., 'en', 'fr', 'de', 'es')
"""
def add(self, lang=None, set_default=True):
"""
Add supported language to locale manager.
Parameters:
- lang (str, optional): Language code to add
- set_default (bool): Set as default language
Returns:
bool: True if language was successfully added
"""
def lang_at(self, lang, mapto=None):
"""
Context manager for temporary language switching.
Parameters:
- lang (str): Target language code
- mapto (callable, optional): Mapping function
Usage:
with locale.lang_at('fr'):
# Code runs with French locale
"""
@property
def gettext(self):
"""
Get gettext function for current language.
Returns:
callable: Gettext function for translations
"""
@staticmethod
def detect_language(lang=None, detect_fallback=True):
"""
Detect system language or validate language code.
Parameters:
- lang (str, optional): Language code to validate
- detect_fallback (bool): Use fallback detection
Returns:
str: Detected or validated language code
"""
@property
def language(self):
"""
Current language code.
Returns:
str: Active language code (e.g., 'en', 'fr', 'de')
"""
@property
def languages(self):
"""
Available supported languages.
Returns:
list: List of supported language codes
"""Apprise includes built-in support for multiple languages:
import apprise
# Create locale manager with specific language
locale = apprise.AppriseLocale(language='fr') # French
# Create Apprise with localized settings
apobj = apprise.Apprise()
apobj.add('mailto://user:pass@gmail.com')
# Messages will use French localization where available
apobj.notify(
body='Votre sauvegarde a été completée avec succès',
title='Statut de sauvegarde',
notify_type=apprise.NotifyType.SUCCESS
)import apprise
locale = apprise.AppriseLocale()
# Switch between languages
languages = ['en', 'fr', 'de', 'es']
for lang in languages:
locale.lang(lang)
print(f"Current language: {locale.language}")
# Get localized text
success_msg = apprise.AppriseLocale.gettext("Notification sent successfully")
error_msg = apprise.AppriseLocale.gettext("Failed to send notification")
print(f" Success: {success_msg}")
print(f" Error: {error_msg}")
print()import apprise
# Set locale to language with complex plural rules
locale = apprise.AppriseLocale(language='ru') # Russian has complex plurals
# Demonstrate plural-aware messages
for count in [0, 1, 2, 5, 21, 22, 25]:
message = apprise.AppriseLocale.ngettext(
"You have {0} new message",
"You have {0} new messages",
count
).format(count)
print(f"Count {count}: {message}")
# Example output for Russian:
# Count 0: У вас 0 новых сообщений
# Count 1: У вас 1 новое сообщение
# Count 2: У вас 2 новых сообщения
# Count 5: У вас 5 новых сообщений
# etc.import apprise
def send_multilingual_notifications(message_data, recipients):
"""
Send notifications in multiple languages based on recipient preferences.
"""
# Message templates in different languages
messages = {
'en': {
'title': 'System Alert',
'body': 'System maintenance will begin in {minutes} minutes'
},
'fr': {
'title': 'Alerte Système',
'body': 'La maintenance système commencera dans {minutes} minutes'
},
'de': {
'title': 'Systemwarnung',
'body': 'Systemwartung beginnt in {minutes} Minuten'
},
'es': {
'title': 'Alerta del Sistema',
'body': 'El mantenimiento del sistema comenzará en {minutes} minutos'
}
}
for recipient in recipients:
# Get recipient's preferred language
lang = recipient.get('language', 'en')
# Create locale for this language
locale = apprise.AppriseLocale(language=lang)
# Get appropriate message template
template = messages.get(lang, messages['en'])
# Format message with data
title = template['title']
body = template['body'].format(**message_data)
# Send notification
apobj = apprise.Apprise()
apobj.add(recipient['notification_url'])
success = apobj.notify(
body=body,
title=title,
notify_type=apprise.NotifyType.WARNING
)
print(f"Sent to {recipient['name']} ({lang}): {'✓' if success else '✗'}")
# Example usage
recipients = [
{
'name': 'John Smith',
'language': 'en',
'notification_url': 'mailto://john@example.com'
},
{
'name': 'Marie Dubois',
'language': 'fr',
'notification_url': 'slack://token/french-team'
},
{
'name': 'Hans Mueller',
'language': 'de',
'notification_url': 'discord://webhook-de'
}
]
message_data = {'minutes': 30}
send_multilingual_notifications(message_data, recipients)import apprise
def handle_localized_errors(language='en'):
"""Demonstrate localized error handling."""
locale = apprise.AppriseLocale(language=language)
apobj = apprise.Apprise()
try:
# Attempt to add invalid service
success = apobj.add('invalid://service/url')
if not success:
error_msg = apprise.AppriseLocale.gettext(
"Failed to add notification service"
)
print(f"Error ({language}): {error_msg}")
except Exception as e:
# Get localized exception message
exception_msg = apprise.AppriseLocale.gettext(
"An unexpected error occurred: {error}"
).format(error=str(e))
print(f"Exception ({language}): {exception_msg}")
# Test error messages in different languages
for lang in ['en', 'fr', 'de', 'es']:
handle_localized_errors(lang)import apprise
import datetime
def send_localized_report(language='en'):
"""Send report with locale-appropriate formatting."""
locale = apprise.AppriseLocale(language=language)
# Format current time according to locale
now = datetime.datetime.now()
# Language-specific date/time formatting
date_formats = {
'en': '%Y-%m-%d %H:%M:%S', # 2025-01-15 14:30:00
'fr': '%d/%m/%Y %H:%M:%S', # 15/01/2025 14:30:00
'de': '%d.%m.%Y %H:%M:%S', # 15.01.2025 14:30:00
'es': '%d/%m/%Y %H:%M:%S', # 15/01/2025 14:30:00
}
date_format = date_formats.get(language, date_formats['en'])
formatted_time = now.strftime(date_format)
# Localized message templates
templates = {
'en': {
'title': 'Daily Report - {date}',
'body': 'System report generated at {time}\nAll systems operational.'
},
'fr': {
'title': 'Rapport Quotidien - {date}',
'body': 'Rapport système généré à {time}\nTous les systèmes sont opérationnels.'
},
'de': {
'title': 'Tagesbericht - {date}',
'body': 'Systembericht erstellt um {time}\nAlle Systeme funktionsfähig.'
},
'es': {
'title': 'Informe Diario - {date}',
'body': 'Informe del sistema generado a las {time}\nTodos los sistemas operativos.'
}
}
template = templates.get(language, templates['en'])
apobj = apprise.Apprise()
apobj.add('mailto://admin@example.com')
success = apobj.notify(
title=template['title'].format(date=formatted_time.split()[0]),
body=template['body'].format(time=formatted_time),
notify_type=apprise.NotifyType.INFO
)
print(f"Report sent in {language}: {'✓' if success else '✗'}")
# Send reports in different languages
for lang in ['en', 'fr', 'de', 'es']:
send_localized_report(lang)import apprise
import json
class CustomLocalization:
"""Custom localization handler with external translation files."""
def __init__(self, translations_dir):
self.translations_dir = translations_dir
self.translations = {}
self.current_language = 'en'
def load_language(self, language):
"""Load translation file for specified language."""
try:
translation_file = f"{self.translations_dir}/{language}.json"
with open(translation_file, 'r', encoding='utf-8') as f:
self.translations[language] = json.load(f)
return True
except FileNotFoundError:
print(f"Translation file not found for {language}")
return False
def set_language(self, language):
"""Set current language and load translations if needed."""
if language not in self.translations:
self.load_language(language)
self.current_language = language
def translate(self, key, **kwargs):
"""Get translated text with variable substitution."""
translations = self.translations.get(self.current_language, {})
text = translations.get(key, key) # Fallback to key if not found
# Substitute variables
try:
return text.format(**kwargs)
except KeyError:
return text
# Example usage with custom translations
def demo_custom_localization():
# Assume we have translation files:
# translations/en.json: {"backup_complete": "Backup completed successfully"}
# translations/fr.json: {"backup_complete": "Sauvegarde terminée avec succès"}
custom_locale = CustomLocalization('/path/to/translations')
# Set up Apprise
apobj = apprise.Apprise()
apobj.add('mailto://user@example.com')
# Send notifications in different languages
for lang in ['en', 'fr', 'de']:
custom_locale.set_language(lang)
message = custom_locale.translate(
'backup_complete',
server='web-01',
time='2025-01-15 14:30'
)
apobj.notify(
body=message,
title=custom_locale.translate('notification_title'),
notify_type=apprise.NotifyType.SUCCESS
)
# demo_custom_localization() # Uncomment when translation files existimport apprise
import locale
import os
def auto_configure_locale():
"""Automatically configure locale based on system settings."""
# Detect system locale
try:
system_locale = locale.getdefaultlocale()[0]
if system_locale:
# Extract language code (e.g., 'en_US' -> 'en')
lang_code = system_locale.split('_')[0]
else:
lang_code = 'en' # Default fallback
except:
lang_code = 'en'
# Check environment variables
env_lang = os.getenv('LANG', '').split('_')[0]
if env_lang:
lang_code = env_lang
# Override with explicit setting if available
apprise_lang = os.getenv('APPRISE_LANG')
if apprise_lang:
lang_code = apprise_lang
print(f"Auto-detected language: {lang_code}")
# Create locale with detected language
apprise_locale = apprise.AppriseLocale(language=lang_code)
# Verify language is supported
if lang_code not in apprise_locale.languages:
print(f"Language {lang_code} not fully supported, falling back to English")
apprise_locale = apprise.AppriseLocale(language='en')
return apprise_locale
# Auto-configure and use
locale_manager = auto_configure_locale()
print(f"Using language: {locale_manager.language}")
print(f"Available languages: {locale_manager.languages}")