django-orchestra-test/orchestra/management/commands/makemessages.py

60 lines
2.1 KiB
Python
Raw Normal View History

2015-03-29 16:10:07 +00:00
import os
from django.core.management.commands import makemessages
from orchestra.core.translations import ModelTranslation
from orchestra.utils.paths import get_site_dir
2015-03-29 16:10:07 +00:00
class Command(makemessages.Command):
""" Provides database translations support """
def handle(self, *args, **options):
self.database_files = []
try:
if os.getcwd() == get_site_dir():
self.generate_database_files()
super(Command, self).handle(*args, **options)
finally:
self.remove_database_files()
2015-03-29 16:10:07 +00:00
def get_contents(self):
for model, fields in ModelTranslation._registry.iteritems():
for field in fields:
contents = []
2015-03-29 16:10:07 +00:00
for content in model.objects.values_list('id', field):
pk, value = content
contents.append(
(pk, u"_(u'%s')" % value)
)
if contents:
yield ('_'.join((model._meta.db_table, field)), contents)
2015-03-29 16:10:07 +00:00
def generate_database_files(self):
"""
Tmp files are generated because:
1) having a nice gettext location
# database_db_table_field.sql.py:id
2) Django's makemessages will work with no modifications
"""
2015-03-29 16:10:07 +00:00
for name, contents in self.get_contents():
name = unicode(name)
maximum = None
content = {}
for pk, value in contents:
if not maximum or pk > maximum:
maximum = pk
content[pk] = value
tmpcontent = []
for ix in xrange(maximum+1):
tmpcontent.append(content.get(ix, ''))
tmpcontent = u'\n'.join(tmpcontent) + '\n'
filename = 'database_%s.sql.py' % name
self.database_files.append(filename)
with open(filename, 'w') as tmpfile:
2015-03-29 16:10:07 +00:00
tmpfile.write(tmpcontent.encode('utf-8'))
def remove_database_files(self):
for path in self.database_files:
2015-03-29 16:10:07 +00:00
os.unlink(path)