Skip to content

Commit 06a5661

Browse files
author
cmlenz
committed
Add Django integration code contributed by Ramiro Morales and Massimo Scamarcia.
git-svn-id: http://svn.edgewall.org/repos/babel/contrib/django@292 59ecc08e-a131-0410-9ea7-d4c0f28ac310
1 parent 2b44f34 commit 06a5661

File tree

7 files changed

+243
-0
lines changed

7 files changed

+243
-0
lines changed

COPYING

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
Copyright (C) 2007 Edgewall Software
2+
All rights reserved.
3+
4+
Redistribution and use in source and binary forms, with or without
5+
modification, are permitted provided that the following conditions
6+
are met:
7+
8+
1. Redistributions of source code must retain the above copyright
9+
notice, this list of conditions and the following disclaimer.
10+
2. Redistributions in binary form must reproduce the above copyright
11+
notice, this list of conditions and the following disclaimer in
12+
the documentation and/or other materials provided with the
13+
distribution.
14+
3. The name of the author may not be used to endorse or promote
15+
products derived from this software without specific prior
16+
written permission.
17+
18+
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
19+
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21+
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
22+
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
24+
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25+
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
26+
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27+
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
28+
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

README.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Tools for using Babel with Django
2+
=================================
3+
4+
This package contains various utilities for integration of Babel into the
5+
Django web framework:
6+
7+
* A message extraction plugin for Django templates.
8+
* A middleware class that adds the Babel `Locale` object to requests.
9+
10+
For more information please visit the wiki page for this package:
11+
12+
<http://babel.edgewall.org/wiki/BabelDjango>

babeldjango/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# Copyright (C) 2007 Edgewall Software
4+
# All rights reserved.
5+
#
6+
# This software is licensed as described in the file COPYING, which
7+
# you should have received as part of this distribution. The terms
8+
# are also available at http://babel.edgewall.org/wiki/License.
9+
#
10+
# This software consists of voluntary contributions made by many
11+
# individuals. For the exact contribution history, see the revision
12+
# history and logs, available at http://babel.edgewall.org/log/.

babeldjango/extract.py

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# Copyright (C) 2007 Edgewall Software
4+
# All rights reserved.
5+
#
6+
# This software is licensed as described in the file COPYING, which
7+
# you should have received as part of this distribution. The terms
8+
# are also available at http://babel.edgewall.org/wiki/License.
9+
#
10+
# This software consists of voluntary contributions made by many
11+
# individuals. For the exact contribution history, see the revision
12+
# history and logs, available at http://babel.edgewall.org/log/.
13+
14+
from babel.core import *
15+
16+
from django.conf import settings
17+
settings.configure(USE_I18N=True)
18+
from django.template import Lexer, TOKEN_TEXT, TOKEN_VAR, TOKEN_BLOCK
19+
from django.utils.translation.trans_real import inline_re, block_re, \
20+
endblock_re, plural_re, \
21+
constant_re
22+
23+
def extract_django(fileobj, keywords, comment_tags, options):
24+
"""Extract messages from Django template files.
25+
26+
:param fileobj: the file-like object the messages should be extracted from
27+
:param keywords: a list of keywords (i.e. function names) that should
28+
be recognized as translation functions
29+
:param comment_tags: a list of translator tags to search for and
30+
include in the results
31+
:param options: a dictionary of additional options (optional)
32+
:return: an iterator over ``(lineno, funcname, message, comments)``
33+
tuples
34+
:rtype: ``iterator``
35+
"""
36+
intrans = False
37+
inplural = False
38+
singular = []
39+
plural = []
40+
lineno = 1
41+
for t in Lexer(fileobj.read(), None).tokenize():
42+
lineno += t.contents.count('\n')
43+
if intrans:
44+
if t.token_type == TOKEN_BLOCK:
45+
endbmatch = endblock_re.match(t.contents)
46+
pluralmatch = plural_re.match(t.contents)
47+
if endbmatch:
48+
if inplural:
49+
yield lineno, 'ngettext', (unicode(''.join(singular)),
50+
unicode(''.join(plural))), []
51+
else:
52+
yield lineno, None, unicode(''.join(singular)), []
53+
intrans = False
54+
inplural = False
55+
singular = []
56+
plural = []
57+
elif pluralmatch:
58+
inplural = True
59+
else:
60+
raise SyntaxError('Translation blocks must not include '
61+
'other block tags: %s' % t.contents)
62+
elif t.token_type == TOKEN_VAR:
63+
if inplural:
64+
plural.append('%%(%s)s' % t.contents)
65+
else:
66+
singular.append('%%(%s)s' % t.contents)
67+
elif t.token_type == TOKEN_TEXT:
68+
if inplural:
69+
plural.append(t.contents)
70+
else:
71+
singular.append(t.contents)
72+
else:
73+
if t.token_type == TOKEN_BLOCK:
74+
imatch = inline_re.match(t.contents)
75+
bmatch = block_re.match(t.contents)
76+
cmatches = constant_re.findall(t.contents)
77+
if imatch:
78+
g = imatch.group(1)
79+
if g[0] == '"':
80+
g = g.strip('"')
81+
elif g[0] == "'":
82+
g = g.strip("'")
83+
yield lineno, None, unicode(g), []
84+
elif bmatch:
85+
intrans = True
86+
inplural = False
87+
singular = []
88+
plural = []
89+
elif cmatches:
90+
for cmatch in cmatches:
91+
yield lineno, None, unicode(cmatch), []
92+
elif t.token_type == TOKEN_VAR:
93+
parts = t.contents.split('|')
94+
cmatch = constant_re.match(parts[0])
95+
if cmatch:
96+
yield lineno, None, unicode(cmatch.group(1)), []
97+
for p in parts[1:]:
98+
if p.find(':_(') >= 0:
99+
p1 = p.split(':',1)[1]
100+
if p1[0] == '_':
101+
p1 = p1[1:]
102+
if p1[0] == '(':
103+
p1 = p1.strip('()')
104+
if p1[0] == "'":
105+
p1 = p1.strip("'")
106+
elif p1[0] == '"':
107+
p1 = p1.strip('"')
108+
yield lineno, None, unicode(p1), []

babeldjango/middleware.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# -*- coding: utf-8 -*-
2+
#
3+
# Copyright (C) 2007 Edgewall Software
4+
# All rights reserved.
5+
#
6+
# This software is licensed as described in the file COPYING, which
7+
# you should have received as part of this distribution. The terms
8+
# are also available at http://babel.edgewall.org/wiki/License.
9+
#
10+
# This software consists of voluntary contributions made by many
11+
# individuals. For the exact contribution history, see the revision
12+
# history and logs, available at http://babel.edgewall.org/log/.
13+
14+
from babel import Locale, UnknownLocaleError
15+
try:
16+
from threading import local
17+
except ImportError:
18+
from django.utils._threading_local import local
19+
20+
__all__ = ['get_current_locale', 'LocaleMiddleware']
21+
22+
_thread_locals = local()
23+
24+
def get_current_locale():
25+
"""Get current locale data outside views.
26+
27+
See http://babel.edgewall.org/wiki/ApiDocs/babel.core for Locale
28+
objects documentation
29+
"""
30+
return getattr(_thread_locals, 'locale', None)
31+
32+
33+
class LocaleMiddleware(object):
34+
"""Simple Django middleware that makes available a Babel `Locale` object
35+
via the `request.locale` attribute.
36+
"""
37+
38+
def process_request(self, request):
39+
try:
40+
locale = Locale.parse(request.LANGUAGE_CODE, sep='-')
41+
except (ValueError, UnknownLocaleError):
42+
pass
43+
else:
44+
_thread_locals.locale = request.locale = locale

setup.cfg

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[egg_info]
2+
tag_build = dev
3+
tag_svn_revision = true

setup.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
#
4+
# Copyright (C) 2007 Edgewall Software
5+
# All rights reserved.
6+
#
7+
# This software is licensed as described in the file COPYING, which
8+
# you should have received as part of this distribution. The terms
9+
# are also available at http://babel.edgewall.org/wiki/License.
10+
#
11+
# This software consists of voluntary contributions made by many
12+
# individuals. For the exact contribution history, see the revision
13+
# history and logs, available at http://babel.edgewall.org/log/.
14+
15+
try:
16+
from setuptools import setup
17+
except ImportError:
18+
from distutils.core import setup
19+
20+
setup(
21+
name = 'BabelDjango',
22+
description = 'Utilities for using Babel in Django',
23+
version = '0.1',
24+
license = 'BSD',
25+
author = 'Edgewall Software',
26+
author_email = '[email protected]',
27+
url = 'http://babel.edgewall.org/wiki/BabelDjango',
28+
29+
packages = ['babeldjango'],
30+
install_requires = ['Babel'],
31+
32+
entry_points = """
33+
[babel.extractors]
34+
django = babeldjango.extract:extract_django
35+
""",
36+
)

0 commit comments

Comments
 (0)