or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdformatting.mdindex.mdtranslation.md

configuration.mddocs/

0

# Application Configuration

1

2

Configuration and setup of Flask-Babel for Flask applications, including the main Babel class, domain management, and context utilities.

3

4

## Types

5

6

```python { .api }

7

from typing import List, Optional, Callable, Union

8

from babel import Locale

9

from babel.support import Translations, NullTranslations

10

from pytz import timezone

11

from werkzeug.datastructures import ImmutableDict

12

```

13

14

## Capabilities

15

16

### Main Babel Class

17

18

The central controller class for configuring Flask-Babel behavior in Flask applications.

19

20

```python { .api }

21

class Babel:

22

def __init__(self, app=None, date_formats=None, configure_jinja=True, *args, **kwargs):

23

"""

24

Creates a new Babel instance.

25

26

Parameters:

27

- app: Flask application instance (optional)

28

- date_formats: Custom date format mappings (optional)

29

- configure_jinja: Whether to configure Jinja2 filters automatically (default: True)

30

"""

31

32

def init_app(self, app, default_locale='en', default_domain='messages',

33

default_translation_directories='translations', default_timezone='UTC',

34

locale_selector=None, timezone_selector=None):

35

"""

36

Initialize Babel for a specific Flask application.

37

38

Parameters:

39

- app: Flask application to configure

40

- default_locale: Default locale string (default: 'en')

41

- default_domain: Default message domain (default: 'messages')

42

- default_translation_directories: Translation directories (default: 'translations')

43

- default_timezone: Default timezone string (default: 'UTC')

44

- locale_selector: Function to select locale for requests (optional)

45

- timezone_selector: Function to select timezone for requests (optional)

46

"""

47

48

def list_translations(self):

49

"""

50

Returns list of all locales that have translations.

51

52

Returns:

53

List of babel.Locale objects for available translations

54

"""

55

56

@property

57

def default_locale(self):

58

"""Default locale as babel.Locale object"""

59

60

@property

61

def default_timezone(self):

62

"""Default timezone as pytz.timezone object"""

63

64

@property

65

def domain(self):

66

"""Message domain as string"""

67

68

@property

69

def domain_instance(self):

70

"""Domain instance for this Babel configuration"""

71

72

default_date_formats: ImmutableDict

73

"""

74

Default date format mappings for datetime formatting.

75

76

Contains format defaults for datetime, date, time formatting including

77

short, medium, long, and full format variants.

78

"""

79

```

80

81

### Domain Management

82

83

Manage translation domains for organizing message catalogs.

84

85

```python { .api }

86

class Domain:

87

def __init__(self, translation_directories=None, domain='messages'):

88

"""

89

Create a localization domain.

90

91

Parameters:

92

- translation_directories: List of directories containing translations

93

- domain: Domain name string (default: 'messages')

94

"""

95

96

def as_default(self):

97

"""Set this domain as default for current request"""

98

99

def gettext(self, string, **variables):

100

"""Translate string in this domain"""

101

102

def ngettext(self, singular, plural, num, **variables):

103

"""Translate plural string in this domain"""

104

105

def pgettext(self, context, string, **variables):

106

"""Translate string with context in this domain"""

107

108

def lazy_gettext(self, string, **variables):

109

"""Return lazy-evaluated translation in this domain"""

110

111

def lazy_ngettext(self, singular, plural, num, **variables):

112

"""Return lazy-evaluated plural translation in this domain"""

113

114

def npgettext(self, context, singular, plural, num, **variables):

115

"""Translate string with context and plural forms in this domain"""

116

117

def get_translations(self):

118

"""

119

Get translations object for this domain.

120

121

Returns:

122

babel.support.Translations or NullTranslations object

123

"""

124

125

def get_translations_cache(self, ctx):

126

"""

127

Get translations cache for this domain.

128

129

Parameters:

130

- ctx: Request context

131

132

Returns:

133

Dictionary-like cache object

134

"""

135

136

@property

137

def translation_directories(self):

138

"""List of translation directories for this domain"""

139

```

140

141

### Context and Configuration Access

142

143

Access current configuration and context information.

144

145

```python { .api }

146

def get_babel(app=None):

147

"""

148

Get BabelConfiguration for app.

149

150

Parameters:

151

- app: Flask app (optional, uses current_app if None)

152

153

Returns:

154

BabelConfiguration instance

155

"""

156

157

def get_locale():

158

"""

159

Get current locale for request.

160

161

Returns:

162

babel.Locale object or None if outside request context

163

"""

164

165

def get_timezone():

166

"""

167

Get current timezone for request.

168

169

Returns:

170

pytz.timezone object or None if outside request context

171

"""

172

173

def get_domain():

174

"""

175

Get current Domain instance.

176

177

Returns:

178

Domain object for current request

179

"""

180

181

def refresh():

182

"""

183

Refresh cached locale and timezone information.

184

Useful when changing locale/timezone mid-request.

185

"""

186

```

187

188

### Context Management

189

190

Temporarily override locale settings.

191

192

```python { .api }

193

def force_locale(locale):

194

"""

195

Context manager to temporarily override locale.

196

197

Parameters:

198

- locale: Locale string (e.g., 'en_US', 'de_DE')

199

200

Usage:

201

with force_locale('de_DE'):

202

message = gettext('Hello') # Returns German translation

203

"""

204

```

205

206

### Configuration Data Classes

207

208

Internal configuration structures.

209

210

```python { .api }

211

@dataclass

212

class BabelConfiguration:

213

"""Application-specific Babel configuration"""

214

default_locale: str

215

default_timezone: str

216

default_domain: str

217

default_directories: List[str]

218

translation_directories: List[str]

219

instance: Babel

220

locale_selector: Optional[Callable] = None

221

timezone_selector: Optional[Callable] = None

222

```

223

224

## Usage Examples

225

226

### Application Factory Pattern

227

228

```python

229

from flask import Flask

230

from flask_babel import Babel

231

232

babel = Babel()

233

234

def create_app():

235

app = Flask(__name__)

236

app.config['BABEL_DEFAULT_LOCALE'] = 'en'

237

238

babel.init_app(app)

239

return app

240

```

241

242

### Custom Locale Selector

243

244

```python

245

from flask import request

246

from flask_babel import Babel

247

248

app = Flask(__name__)

249

250

@babel.localeselector

251

def get_locale():

252

# Check URL parameter first

253

if 'lang' in request.args:

254

return request.args['lang']

255

# Fall back to browser preference

256

return request.accept_languages.best_match(['en', 'es', 'fr', 'de'])

257

```

258

259

### Multiple Domains

260

261

```python

262

from flask_babel import Domain

263

264

# Create domains for different parts of application

265

admin_domain = Domain(domain='admin')

266

user_domain = Domain(domain='user')

267

268

# Use specific domain

269

admin_message = admin_domain.gettext('Admin Dashboard')

270

user_message = user_domain.gettext('Welcome')

271

```