config.py 2.31 KB
Newer Older
1
import os, json
2
from path import path
3 4 5

# BASE_DIR is the working directory to execute django-admin commands from.
# Typically this should be the 'mitx' directory.
6
BASE_DIR = path(__file__).abspath().dirname().joinpath('..').normpath()
7 8 9

# LOCALE_DIR contains the locale files.
# Typically this should be 'mitx/conf/locale'
10
LOCALE_DIR =  BASE_DIR.joinpath('conf', 'locale')
11 12 13 14 15 16 17 18 19

class Configuration:
    """
    # Reads localization configuration in json format

    """
    _source_locale = 'en'

    def __init__(self, filename):
20 21
        self._filename = filename
        self._config = self.read_config(filename)
22

23
    def read_config(self, filename):
24 25 26 27 28 29 30 31
        """
        Returns data found in config file (as dict), or raises exception if file not found
        """
        if not os.path.exists(filename):
            raise Exception("Configuration file cannot be found: %s" % filename)
        with open(filename) as stream:
            return json.load(stream)

32 33
    @property
    def locales(self):
34 35 36 37 38
        """
        Returns a list of locales declared in the configuration file,
        e.g. ['en', 'fr', 'es']
        Each locale is a string.
        """
39
        return self._config['locales']
40

41 42
    @property
    def source_locale(self):
43 44 45 46 47 48
        """
        Returns source language.
        Source language is English.
        """
        return self._source_locale

49 50
    @property
    def dummy_locale(self):
51 52 53 54 55
        """
        Returns a locale to use for the dummy text, e.g. 'fr'.
        Throws exception if no dummy-locale is declared. 
        The locale is a string.
        """
56
        dummy = self._config.get('dummy-locale', None)
57 58 59 60 61 62 63 64 65
        if not dummy:
            raise Exception('Could not read dummy-locale from configuration file.')
        return dummy

    def get_messages_dir(self, locale):
        """
        Returns the name of the directory holding the po files for locale.
        Example: mitx/conf/locale/fr/LC_MESSAGES
        """
66
        return LOCALE_DIR.joinpath(locale, 'LC_MESSAGES')
67

68 69
    @property
    def source_messages_dir(self):
70 71 72 73
        """
        Returns the name of the directory holding the source-language po files (English).
        Example: mitx/conf/locale/en/LC_MESSAGES
        """
74
        return self.get_messages_dir(self.source_locale)
75 76


77
CONFIGURATION = Configuration(LOCALE_DIR.joinpath('config').normpath())