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):
2015-04-02 16:14:55 +00:00
for model, fields in ModelTranslation._registry.items():
2015-03-29 16:10:07 +00:00
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(
2015-04-02 16:14:55 +00:00
(pk, "_(u'%s')" % value)
2015-03-29 16:10:07 +00:00
)
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():
2015-04-02 16:14:55 +00:00
name = str(name)
2015-03-29 16:10:07 +00:00
maximum = None
content = {}
for pk, value in contents:
if not maximum or pk > maximum:
maximum = pk
content[pk] = value
tmpcontent = []
2015-04-02 16:14:55 +00:00
for ix in range(maximum+1):
2015-03-29 16:10:07 +00:00
tmpcontent.append(content.get(ix, ''))
2015-04-02 16:14:55 +00:00
tmpcontent = '\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)