Python Integration

A framework-agnostic Python SDK for the AutoLocalise translation service. Works seamlessly with Django, Flask, FastAPI, or any Python backend.

Prerequisites

pip install autolocalise

Key Features

  • Framework-agnostic — Works with any Python web framework
  • Intelligent caching — In-memory cache with thread-safe operations
  • Template support — Built-in Python Template support with parameter protection
  • Batch translation — Efficient bulk translation support
  • Smart API usage — Only translates new strings, reuses existing translations
  • Error handling — Graceful fallbacks when translation fails

1. Quick Start

from autolocalise import Translator

# Initialize translator
translator = Translator(
    api_key="your-api-key",
    source_locale="en",
    target_locale="fr"
)

# Simple translation
result = translator.translate(["Hello", "Goodbye"])
print(result)
# {"Hello": "Bonjour", "Goodbye": "Au revoir"}

# Template with parameters
from string import Template
template = Template("Hello $name, you have $count new messages!")
translated = translator.translate_template(template, name="Alice", count=5)
print(translated)
# "Bonjour Alice, vous avez 5 nouveaux messages!"

2. Core Usage

Basic Translation

from autolocalise import Translator

translator = Translator(
    api_key="your-api-key",
    source_locale="en",
    target_locale="fr"
)

# Single or multiple texts
texts = ["Welcome", "Login", "Submit"]
translations = translator(texts)

Template Translation with Parameters

The SDK supports Python's string.Template with automatic parameter protection:

from string import Template
from autolocalise import Translator

translator = Translator(
    api_key="your-api-key",
    source_locale="en",
    target_locale="fr"
)

# Create template
template = Template("Welcome $name! You have $count items in your $container.")

# Translate with parameters - parameters are protected from translation
result = translator.translate_template(template, name="John", count=3, container="cart")
print(result)
# "Bienvenue John! Vous avez 3 articles dans votre cart."

Environment Configuration

import os
from autolocalise import Translator

translator = Translator(
    api_key=os.getenv("AUTOLOCALISE_API_KEY"),
    source_locale=os.getenv("AUTOLOCALISE_SOURCE_LANG", "en"),
    target_locale=os.getenv("AUTOLOCALISE_TARGET_LANG", "fr")
)

3. Framework Examples

Django

# utils.py
from django.conf import settings
from autolocalise import Translator
from string import Template

translator = Translator(
    api_key=settings.AUTOLOCALISE_API_KEY,
    source_locale="en",
    target_locale="fr"
)

def translate_message(template_str, **params):
    template = Template(template_str)
    return translator.translate_template(template, **params)

# views.py
def dashboard_view(request):
    message = translate_message(
        "Hello $name, you have $count notifications!",
        name=request.user.first_name,
        count=request.user.notifications.unread().count()
    )
    return render(request, 'dashboard.html', {'message': message})

Django Settings Configuration

# settings.py
import os

AUTOLOCALISE_API_KEY = os.getenv('AUTOLOCALISE_API_KEY')
AUTOLOCALISE_SOURCE_LANG = os.getenv('AUTOLOCALISE_SOURCE_LANG', 'en')
AUTOLOCALISE_TARGET_LANG = os.getenv('AUTOLOCALISE_TARGET_LANG', 'fr')

Flask

from flask import Flask
from autolocalise import Translator
from string import Template

app = Flask(__name__)
translator = Translator(
    api_key=app.config['AUTOLOCALISE_API_KEY'],
    source_locale="en",
    target_locale="fr"
)

@app.route('/user/<username>')
def user_profile(username):
    template = Template("Welcome back, $name!")
    message = translator.translate_template(template, name=username)
    return f"<h1>{message}</h1>"

# With Jinja2 templates
@app.template_filter('translate')
def translate_filter(text):
    result = translator.translate([text])
    return result.get(text, text)

# Usage in templates: {{ "Hello World" | translate }}

Flask Configuration

# config.py
import os

class Config:
    AUTOLOCALISE_API_KEY = os.environ.get('AUTOLOCALISE_API_KEY')
    AUTOLOCALISE_SOURCE_LANG = os.environ.get('AUTOLOCALISE_SOURCE_LANG', 'en')
    AUTOLOCALISE_TARGET_LANG = os.environ.get('AUTOLOCALISE_TARGET_LANG', 'fr')

# app.py
app.config.from_object(Config)

FastAPI

from fastapi import FastAPI, Depends
from autolocalise import Translator
from string import Template

app = FastAPI()

def get_translator():
    return Translator(
        api_key="your-api-key",
        source_locale="en",
        target_locale="fr"
    )

@app.get("/welcome/{user_name}")
async def welcome_user(user_name: str, translator: Translator = Depends(get_translator)):
    template = Template("Welcome $name! Enjoy using our API.")
    message = translator.translate_template(template, name=user_name)
    return {"message": message}

@app.get("/translate")
async def translate_text(text: str, target_locale: str = "fr", translator: Translator = Depends(get_translator)):
    # Override target locale for this request
    custom_translator = Translator(
        api_key="your-api-key",
        source_locale="en",
        target_locale=target_locale
    )
    result = custom_translator.translate([text])
    return {"original": text, "translated": result.get(text, text), "locale": target_locale}

Cache Management

# Check cache size
cache_size = translator.cache_size()

# Clear instance cache
translator.clear_cache()

# Clear global cache (affects all translator instances)
Translator.clear_global_cache()

4. How Parameter Protection Works

When using translate_template():

  1. Parameter Extraction: Parameters are temporarily replaced with short placeholders like X1X, X2X
  2. Translation: Only the template text with placeholders is sent for translation
  3. Parameter Restoration: Original parameter values are substituted back
  4. Result: Translated text with original parameter values intact

Cost Optimization: Short placeholders minimize translation API costs while ensuring parameters like usernames, numbers, and dynamic content are never accidentally translated.

Example: "Hello $name!""Hello X1X!" (sent to API) → "Bonjour John!" (final result)

5 Advanced Usage

Batch Translation with Different Locales

translator = Translator(api_key="your-api-key", source_locale="en")

# Translate to French
french_translations = translator.translate(["Hello", "Goodbye"], target_locale="fr")
# {"Hello": "Bonjour", "Goodbye": "Au revoir"}

# Translate to Spanish
spanish_translations = translator.translate(["Hello", "Goodbye"], target_locale="es")
# {"Hello": "Hola", "Goodbye": "Adiós"}

6. Best Practices

Performance Optimization

  • Use batch translation: Translate multiple strings at once
  • Enable caching: Keep cache_enabled=True for better performance
  • Reuse translator instances: Don't create new instances for each translation
  • Use shared cache: Keep shared_cache=True to share translations across instances

Template Design

  • Use descriptive placeholders: $username instead of $u
  • Keep templates simple: Break complex templates into smaller ones
  • Protect user data: Parameters are automatically protected from translation

8. Migration from Other Solutions

From Manual String Management

# Before: Manual dictionary management
translations = {
    "en": {"welcome": "Welcome"},
    "fr": {"welcome": "Bienvenue"}
}

# After: AutoLocalise
translator = Translator(api_key="your-api-key", source_locale="en", target_locale="fr")
result = translator.translate(["Welcome"])
welcome_text = result["Welcome"]

From gettext

# Before: gettext
import gettext
_ = gettext.gettext
text = _("Welcome to our app")

# After: AutoLocalise
translator = Translator(api_key="your-api-key", source_locale="en", target_locale="fr")
result = translator.translate(["Welcome to our app"])
text = result["Welcome to our app"]

Next Steps