Firebase Admin Python SDK enables server-side Python developers to integrate Firebase services into their applications from privileged environments.
—
Firebase Remote Config server-side template management for dynamic app configuration without requiring app updates. Enables A/B testing, feature flags, and runtime configuration management.
Manage Remote Config templates on the server side with evaluation and configuration capabilities.
class ServerTemplate:
"""Server-side Remote Config template management."""
def load(self):
"""
Load the current Remote Config template from Firebase.
This method fetches the latest template configuration from
the Firebase Remote Config service.
"""
def evaluate(self, context=None):
"""
Evaluate the template with optional context.
Args:
context: EvaluationContext instance for personalized config (optional)
Returns:
ServerConfig: Evaluated configuration values
"""
def set(self, template_data_json):
"""
Set the Remote Config template data.
Args:
template_data_json: JSON string representing the template configuration
"""
class ServerConfig:
"""Evaluated Remote Config results."""
def get_value(self, key):
"""
Get a configuration value by key.
Args:
key: Configuration parameter key string
Returns:
Value: Configuration value with metadata
"""
def get_boolean(self, key):
"""
Get a boolean configuration value.
Args:
key: Configuration parameter key string
Returns:
bool: Boolean value of the parameter
"""
def get_number(self, key):
"""
Get a numeric configuration value.
Args:
key: Configuration parameter key string
Returns:
float: Numeric value of the parameter
"""
def get_string(self, key):
"""
Get a string configuration value.
Args:
key: Configuration parameter key string
Returns:
str: String value of the parameter
"""Remote Config templates define parameters with default values and conditional rules:
{
"parameters": {
"welcome_message": {
"defaultValue": {
"value": "Welcome to our app!"
},
"conditionalValues": {
"premium_users": {
"value": "Welcome back, premium user!"
}
}
},
"feature_enabled": {
"defaultValue": {
"value": "false"
},
"conditionalValues": {
"beta_group": {
"value": "true"
}
}
},
"max_items": {
"defaultValue": {
"value": "10"
}
}
},
"conditions": [
{
"name": "premium_users",
"expression": "user.subscription == 'premium'"
},
{
"name": "beta_group",
"expression": "user.inRandomPercentile <= 10"
}
],
"parameterGroups": {},
"version": {
"versionNumber": "42",
"updateTime": "2024-01-15T10:30:00Z",
"updateUser": "admin@example.com",
"updateOrigin": "ADMIN_SDK_PYTHON"
}
}class EvaluationContext:
"""Context for evaluating Remote Config conditions."""
def __init__(self, user_properties=None):
"""
Initialize evaluation context.
Args:
user_properties: Dict of user properties for condition evaluation
"""
class Value:
"""Remote Config parameter value with metadata."""
@property
def value(self):
"""The parameter value as string."""
@property
def source(self):
"""The source of this value (DEFAULT, REMOTE, etc.)."""from firebase_admin import remote_config
# Create server template instance
template = remote_config.ServerTemplate()
# Load current template from Firebase
template.load()
# Evaluate configuration for a user
context = remote_config.EvaluationContext({
'user_id': 'user123',
'subscription': 'premium',
'app_version': '2.1.0'
})
config = template.evaluate(context)
# Get configuration values
welcome_message = config.get_string('welcome_message')
feature_enabled = config.get_boolean('feature_enabled')
max_items = config.get_number('max_items')
print(f'Welcome: {welcome_message}')
print(f'Feature enabled: {feature_enabled}')
print(f'Max items: {max_items}')import json
from firebase_admin import remote_config
# Define template configuration
template_config = {
"parameters": {
"app_theme": {
"defaultValue": {
"value": "light"
},
"conditionalValues": {
"dark_mode_users": {
"value": "dark"
}
}
},
"api_timeout": {
"defaultValue": {
"value": "30"
},
"conditionalValues": {
"slow_connection": {
"value": "60"
}
}
},
"new_feature_rollout": {
"defaultValue": {
"value": "false"
},
"conditionalValues": {
"feature_rollout_10_percent": {
"value": "true"
}
}
}
},
"conditions": [
{
"name": "dark_mode_users",
"expression": "user.preferences.theme == 'dark'"
},
{
"name": "slow_connection",
"expression": "user.connectionType == 'slow'"
},
{
"name": "feature_rollout_10_percent",
"expression": "user.inRandomPercentile <= 10"
}
]
}
# Set template configuration
template = remote_config.ServerTemplate()
template.set(json.dumps(template_config))# Evaluate for different user contexts
users = [
{
'user_id': 'user1',
'preferences': {'theme': 'dark'},
'connectionType': 'fast',
'inRandomPercentile': 5
},
{
'user_id': 'user2',
'preferences': {'theme': 'light'},
'connectionType': 'slow',
'inRandomPercentile': 25
},
{
'user_id': 'user3',
'preferences': {'theme': 'light'},
'connectionType': 'fast',
'inRandomPercentile': 95
}
]
template = remote_config.ServerTemplate()
template.load()
for user in users:
context = remote_config.EvaluationContext(user)
config = template.evaluate(context)
theme = config.get_string('app_theme')
timeout = config.get_number('api_timeout')
new_feature = config.get_boolean('new_feature_rollout')
print(f'User {user["user_id"]}:')
print(f' Theme: {theme}')
print(f' Timeout: {timeout}s')
print(f' New feature: {new_feature}')
print()# Configure A/B test parameters
ab_test_config = {
"parameters": {
"button_color": {
"defaultValue": {
"value": "blue"
},
"conditionalValues": {
"variant_a": {
"value": "green"
},
"variant_b": {
"value": "red"
}
}
},
"checkout_flow": {
"defaultValue": {
"value": "standard"
},
"conditionalValues": {
"variant_a": {
"value": "simplified"
},
"variant_b": {
"value": "express"
}
}
}
},
"conditions": [
{
"name": "variant_a",
"expression": "user.experimentGroup == 'A'"
},
{
"name": "variant_b",
"expression": "user.experimentGroup == 'B'"
}
]
}
template = remote_config.ServerTemplate()
template.set(json.dumps(ab_test_config))
# Evaluate for A/B test participants
test_users = [
{'user_id': 'user1', 'experimentGroup': 'A'},
{'user_id': 'user2', 'experimentGroup': 'B'},
{'user_id': 'user3', 'experimentGroup': 'control'}
]
for user in test_users:
context = remote_config.EvaluationContext(user)
config = template.evaluate(context)
button_color = config.get_string('button_color')
checkout_flow = config.get_string('checkout_flow')
print(f'User {user["user_id"]} (Group {user["experimentGroup"]}):')
print(f' Button color: {button_color}')
print(f' Checkout flow: {checkout_flow}')# Feature flag configuration
feature_flags_config = {
"parameters": {
"payment_methods_v2": {
"defaultValue": {
"value": "false"
},
"conditionalValues": {
"beta_testers": {
"value": "true"
},
"gradual_rollout": {
"value": "true"
}
}
},
"analytics_enhanced": {
"defaultValue": {
"value": "false"
},
"conditionalValues": {
"premium_tier": {
"value": "true"
}
}
}
},
"conditions": [
{
"name": "beta_testers",
"expression": "user.role == 'beta_tester'"
},
{
"name": "gradual_rollout",
"expression": "user.inRandomPercentile <= 25"
},
{
"name": "premium_tier",
"expression": "user.subscription in ['premium', 'enterprise']"
}
]
}
template = remote_config.ServerTemplate()
template.set(json.dumps(feature_flags_config))
# Check feature availability for users
def check_features_for_user(user_data):
context = remote_config.EvaluationContext(user_data)
config = template.evaluate(context)
return {
'payment_v2': config.get_boolean('payment_methods_v2'),
'enhanced_analytics': config.get_boolean('analytics_enhanced')
}
# Example user checks
users = [
{'user_id': 'beta1', 'role': 'beta_tester', 'subscription': 'free'},
{'user_id': 'premium1', 'role': 'user', 'subscription': 'premium'},
{'user_id': 'regular1', 'role': 'user', 'subscription': 'free', 'inRandomPercentile': 15}
]
for user in users:
features = check_features_for_user(user)
print(f'User {user["user_id"]} features: {features}')# Track configuration value sources
template = remote_config.ServerTemplate()
template.load()
context = remote_config.EvaluationContext({
'user_id': 'user123',
'subscription': 'premium'
})
config = template.evaluate(context)
# Get value with source information
welcome_value = config.get_value('welcome_message')
print(f'Welcome message: {welcome_value.value}')
print(f'Source: {welcome_value.source}')
feature_value = config.get_value('feature_enabled')
print(f'Feature enabled: {feature_value.value}')
print(f'Source: {feature_value.source}')Remote Config supports complex condition expressions for sophisticated targeting:
# Examples of condition expressions:
conditions = [
# User demographics
"user.age >= 18 && user.age <= 65",
"user.country in ['US', 'CA', 'UK']",
"user.language == 'en'",
# App context
"app.version >= '2.0.0'",
"device.os == 'iOS'",
"device.model in ['iPhone12', 'iPhone13']",
# Behavioral targeting
"user.sessionCount >= 5",
"user.purchaseHistory.total > 100",
"user.lastActiveDate > '2024-01-01'",
# Time-based conditions
"percent <= 10", # 10% rollout
"user.inRandomPercentile <= 25", # 25% of users
# Combined conditions
"user.subscription == 'premium' && user.country == 'US'",
"(user.age >= 18 && user.age <= 25) || user.role == 'student'"
]class ConfigService:
def __init__(self):
self.template = remote_config.ServerTemplate()
self.template.load()
def get_user_config(self, user_data):
context = remote_config.EvaluationContext(user_data)
return self.template.evaluate(context)
def refresh_template(self):
"""Refresh template from Firebase (call periodically)"""
self.template.load()
# Usage in web application
config_service = ConfigService()
def handle_user_request(user_id, user_properties):
config = config_service.get_user_config(user_properties)
# Use configuration in application logic
theme = config.get_string('app_theme')
timeout = config.get_number('api_timeout')
return render_response(theme=theme, timeout=timeout)class ServerTemplate:
"""Server-side Remote Config template management."""
def load(self):
"""Load the current template from Firebase."""
def evaluate(self, context=None):
"""Evaluate template with context."""
def set(self, template_data_json):
"""Set template configuration."""
class ServerConfig:
"""Evaluated Remote Config results."""
def get_value(self, key):
"""Get configuration value with metadata."""
def get_boolean(self, key):
"""Get boolean configuration value."""
def get_number(self, key):
"""Get numeric configuration value."""
def get_string(self, key):
"""Get string configuration value."""
class EvaluationContext:
"""Context for evaluating Remote Config conditions."""
def __init__(self, user_properties=None):
"""Initialize with user properties dict."""
class Value:
"""Remote Config parameter value with metadata."""
@property
def value(self):
"""The parameter value as string."""
@property
def source(self):
"""The source of this value."""Install with Tessl CLI
npx tessl i tessl/pypi-firebase-admin