Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed #740 -- Abstracted hard-coded slash in utils/translation.py. Th…

…anks, radek. Also cleaned up docstrings a bit.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@1095 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit d5368d341c65a9b0606193f06bb017e51eb71d00 1 parent f6ce403
Adrian Holovaty authored

Showing 1 changed file with 55 additions and 83 deletions. Show diff stats Hide diff stats

  1. 138  django/utils/translation.py
138  django/utils/translation.py
... ...
@@ -1,11 +1,8 @@
1 1
 "translation helper functions"
2 2
 
3  
-import os
4  
-import re
5  
-import sys
  3
+import os, re, sys
6 4
 import gettext as gettext_module
7 5
 from cStringIO import StringIO
8  
-
9 6
 from django.utils.functional import lazy
10 7
 
11 8
 try:
@@ -20,22 +17,20 @@
20 17
     def currentThread():
21 18
         return 'no threading'
22 19
 
23  
-# translations are cached in a dictionary for
24  
-# every language+app tuple. The active translations
25  
-# are stored by threadid to make them thread local.
  20
+# Translations are cached in a dictionary for every language+app tuple.
  21
+# The active translations are stored by threadid to make them thread local.
26 22
 _translations = {}
27 23
 _active = {}
28 24
 
29  
-# the default translation is based on the settings file
  25
+# The default translation is based on the settings file.
30 26
 _default = None
31 27
 
32  
-# this is a cache for accept-header to translation
33  
-# object mappings to prevent the accept parser to
34  
-# run multiple times for one user
  28
+# This is a cache for accept-header to translation object mappings to prevent
  29
+# the accept parser to run multiple times for one user.
35 30
 _accepted = {}
36 31
 
37 32
 def to_locale(language):
38  
-    "turn a language name (en-us) into a locale name (en_US)"
  33
+    "Turns a language name (en-us) into a locale name (en_US)."
39 34
     p = language.find('-')
40 35
     if p >= 0:
41 36
         return language[:p].lower()+'_'+language[p+1:].upper()
@@ -43,7 +38,7 @@ def to_locale(language):
43 38
         return language.lower()
44 39
 
45 40
 def to_language(locale):
46  
-    "turns a locale name (en_US) into a language name (en-us)"
  41
+    "Turns a locale name (en_US) into a language name (en-us)."
47 42
     p = locale.find('_')
48 43
     if p >= 0:
49 44
         return locale[:p].lower()+'-'+locale[p+1:].lower()
@@ -52,16 +47,14 @@ def to_language(locale):
52 47
 
53 48
 class DjangoTranslation(gettext_module.GNUTranslations):
54 49
     """
55  
-    This class sets up the GNUTranslations context with
56  
-    regard to output charset. Django uses a defined
57  
-    DEFAULT_CHARSET as the output charset on Python 2.4 -
58  
-    with Python 2.3, you need to use DjangoTranslation23.
  50
+    This class sets up the GNUTranslations context with regard to output
  51
+    charset. Django uses a defined DEFAULT_CHARSET as the output charset on
  52
+    Python 2.4. With Python 2.3, use DjangoTranslation23.
59 53
     """
60  
-
61 54
     def __init__(self, *args, **kw):
62 55
         from django.conf import settings
63 56
         gettext_module.GNUTranslations.__init__(self, *args, **kw)
64  
-        # starting with Python 2.4, there is a function to define
  57
+        # Starting with Python 2.4, there's a function to define
65 58
         # the output charset. Before 2.4, the output charset is
66 59
         # identical with the translation file charset.
67 60
         try:
@@ -73,29 +66,25 @@ def __init__(self, *args, **kw):
73 66
 
74 67
     def merge(self, other):
75 68
         self._catalog.update(other._catalog)
76  
-    
  69
+
77 70
     def set_language(self, language):
78 71
         self.__language = language
79 72
 
80 73
     def language(self):
81 74
         return self.__language
82  
-    
  75
+
83 76
     def __repr__(self):
84 77
         return "<DjangoTranslation lang:%s>" % self.__language
85 78
 
86  
-
87 79
 class DjangoTranslation23(DjangoTranslation):
88  
-
89 80
     """
90  
-    This is a compatibility class that is only used with Python 2.3.
91  
-    The reason is, Python 2.3 doesn't support set_output_charset on
92  
-    translation objects and so needs this wrapper class to make sure
93  
-    that input charsets from translation files are correctly translated
94  
-    to output charsets.
  81
+    Compatibility class that is only used with Python 2.3.
  82
+    Python 2.3 doesn't support set_output_charset on translation objects and
  83
+    needs this wrapper class to make sure input charsets from translation files
  84
+    are correctly translated to output charsets.
95 85
 
96 86
     With a full switch to Python 2.4, this can be removed from the source.
97 87
     """
98  
-
99 88
     def gettext(self, msgid):
100 89
         res = self.ugettext(msgid)
101 90
         return res.encode(self.django_output_charset)
@@ -106,20 +95,19 @@ def ngettext(self, msgid1, msgid2, n):
106 95
 
107 96
 def translation(language):
108 97
     """
109  
-    This function returns a translation object.  app must be the fully
110  
-    qualified name of the application.
  98
+    Returns a translation object.
111 99
 
112 100
     This translation object will be constructed out of multiple GNUTranslations
113  
-    objects by merging their catalogs. It will construct a object for the requested
114  
-    language and add a fallback to the default language, if that is different
115  
-    from the requested language.
  101
+    objects by merging their catalogs. It will construct a object for the
  102
+    requested language and add a fallback to the default language, if it's
  103
+    different from the requested language.
116 104
     """
117 105
     global _translations
118 106
 
119 107
     t = _translations.get(language, None)
120 108
     if t is not None:
121 109
         return t
122  
-    
  110
+
123 111
     from django.conf import settings
124 112
 
125 113
     # set up the right translation class
@@ -150,7 +138,7 @@ def _translation(path):
150 138
                 return t
151 139
             except IOError, e:
152 140
                 return None
153  
-    
  141
+
154 142
         res = _translation(globalpath)
155 143
 
156 144
         def _merge(path):
@@ -181,7 +169,7 @@ def _merge(path):
181 169
 
182 170
             if os.path.isdir(apppath):
183 171
                 res = _merge(apppath)
184  
-  
  172
+
185 173
         if res is None:
186 174
             if fallback is not None:
187 175
                 res = fallback
@@ -197,49 +185,41 @@ def _merge(path):
197 185
 
198 186
 def activate(language):
199 187
     """
200  
-    This function fetches the translation object for a given
201  
-    tuple of application name and language and installs it as
202  
-    the current translation object for the current thread.
  188
+    Fetches the translation object for a given tuple of application name and
  189
+    language and installs it as the current translation object for the current
  190
+    thread.
203 191
     """
204 192
     _active[currentThread()] = translation(language)
205 193
 
206 194
 def deactivate():
207 195
     """
208  
-    This function deinstalls the currently active translation
209  
-    object so that further _ calls will resolve against the
210  
-    default translation object, again.
  196
+    Deinstalls the currently active translation object so that further _ calls
  197
+    will resolve against the default translation object, again.
211 198
     """
212 199
     global _active
213  
-
214 200
     if _active.has_key(currentThread()):
215 201
         del _active[currentThread()]
216 202
 
217 203
 def get_language():
218  
-    """
219  
-    This function returns the currently selected language.
220  
-    """
  204
+    "Returns the currently selected language."
221 205
     t = _active.get(currentThread(), None)
222 206
     if t is not None:
223 207
         try:
224 208
             return to_language(t.language())
225 209
         except AttributeError:
226 210
             pass
227  
-    # if we don't have a real translation object, we assume
228  
-    # it's the default language.
  211
+    # If we don't have a real translation object, assume it's the default language.
229 212
     from django.conf.settings import LANGUAGE_CODE
230 213
     return LANGUAGE_CODE
231 214
 
232 215
 def gettext(message):
233 216
     """
234  
-    This function will be patched into the builtins module to
235  
-    provide the _ helper function. It will use the current
236  
-    thread as a discriminator to find the translation object
237  
-    to use. If no current translation is activated, the
238  
-    message will be run through the default translation
239  
-    object.
  217
+    This function will be patched into the builtins module to provide the _
  218
+    helper function. It will use the current thread as a discriminator to find
  219
+    the translation object to use. If no current translation is activated, the
  220
+    message will be run through the default translation object.
240 221
     """
241 222
     global _default, _active
242  
-
243 223
     t = _active.get(currentThread(), None)
244 224
     if t is not None:
245 225
         return t.gettext(message)
@@ -250,18 +230,15 @@ def gettext(message):
250 230
 
251 231
 def gettext_noop(message):
252 232
     """
253  
-    This function is used to just mark strings for translation
254  
-    but to not translate them now. This can be used to store
255  
-    strings in global variables that should stay in the base
256  
-    language (because they might be used externally) and will
257  
-    be translated later on.
  233
+    Marks strings for translation but doesn't translate them now. This can be
  234
+    used to store strings in global variables that should stay in the base
  235
+    language (because they might be used externally) and will be translated later.
258 236
     """
259 237
     return message
260 238
 
261 239
 def ngettext(singular, plural, number):
262 240
     """
263  
-    This function returns the translation of either the singular
264  
-    or plural, based on the number.
  241
+    Returns the translation of either the singular or plural, based on the number.
265 242
     """
266 243
     global _default, _active
267 244
 
@@ -278,9 +255,8 @@ def ngettext(singular, plural, number):
278 255
 
279 256
 def check_for_language(lang_code):
280 257
     """
281  
-    This function checks wether there is a global language
282  
-    file for the given language code. This is used to decide
283  
-    wether a user-provided language is available.
  258
+    Checks whether there is a global language file for the given language code.
  259
+    This is used to decide whether a user-provided language is available.
284 260
     """
285 261
     from django.conf import settings
286 262
     globalpath = os.path.join(os.path.dirname(settings.__file__), 'locale')
@@ -291,11 +267,9 @@ def check_for_language(lang_code):
291 267
 
292 268
 def get_language_from_request(request):
293 269
     """
294  
-    analyze the request to find what language the user
295  
-    wants the system to show.
  270
+    Analyzes the request to find what language the user wants the system to show.
296 271
     """
297 272
     global _accepted
298  
-
299 273
     from django.conf import settings
300 274
     globalpath = os.path.join(os.path.dirname(settings.__file__), 'locale')
301 275
 
@@ -303,11 +277,11 @@ def get_language_from_request(request):
303 277
         lang_code = request.session.get('django_language', None)
304 278
         if lang_code is not None and check_for_language(lang_code):
305 279
             return lang_code
306  
-    
  280
+
307 281
     lang_code = request.COOKIES.get('django_language', None)
308 282
     if lang_code is not None and check_for_language(lang_code):
309 283
         return lang_code
310  
-    
  284
+
311 285
     accept = request.META.get('HTTP_ACCEPT_LANGUAGE', None)
312 286
     if accept is not None:
313 287
 
@@ -338,25 +312,24 @@ def _parsed(el):
338 312
                 # filename, because otherwise we might incorrectly
339 313
                 # report de_DE if we only have de available, but
340 314
                 # did find de_DE because of language normalization
341  
-                lang = langfile[len(globalpath):].split('/')[1]
  315
+                lang = langfile[len(globalpath):].split(os.path.sep)[1]
342 316
                 _accepted[accept] = lang
343 317
                 return lang
344  
-    
  318
+
345 319
     return settings.LANGUAGE_CODE
346 320
 
347 321
 def install():
348 322
     """
349  
-    This installs the gettext function as the default
350  
-    translation function under the name _.
  323
+    Installs the gettext function as the default translation function under
  324
+    the name _.
351 325
     """
352 326
     __builtins__['_'] = gettext
353 327
 
354  
-
355 328
 dot_re = re.compile(r'\S')
356 329
 def blankout(src, char):
357 330
     """
358  
-    This is used in the templateize function and changes every
359  
-    non-whitespace character to the given char.
  331
+    Changes every non-whitespace character to the given char.
  332
+    Used in the templateize function.
360 333
     """
361 334
     return dot_re.sub(char, src)
362 335
 
@@ -368,9 +341,9 @@ def blankout(src, char):
368 341
 def templateize(src):
369 342
     from django.core.template import tokenize, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK
370 343
     """
371  
-    This function turns a django template into something that is
372  
-    understood by xgettext. It does so by translating the django
373  
-    translation tags into standard gettext function invocations.
  344
+    Turns a Django template into something that is understood by xgettext. It
  345
+    does so by translating the Django translation tags into standard gettext
  346
+    function invocations.
374 347
     """
375 348
     out = StringIO()
376 349
     intrans = False
@@ -400,7 +373,7 @@ def templateize(src):
400 373
                 elif pluralmatch:
401 374
                     inplural = True
402 375
                 else:
403  
-                    raise SyntaxError, "translation blocks must not include other block tags: %s" % t.contents
  376
+                    raise SyntaxError, "Translation blocks must not include other block tags: %s" % t.contents
404 377
             elif t.token_type == TOKEN_VAR:
405 378
                 if inplural:
406 379
                     plural.append('%%(%s)s' % t.contents)
@@ -444,4 +417,3 @@ def templateize(src):
444 417
             else:
445 418
                 out.write(blankout(t.contents, 'X'))
446 419
     return out.getvalue()
447  
-

0 notes on commit d5368d3

Please sign in to comment.
Something went wrong with that request. Please try again.