Esempio n. 1
0
 def get_parser(self, ini_filename='test.ini'):
     medici = AssetResolver('pyramid_analytics')
     app_path = medici.resolve('').abspath()
     project_path = path.split(app_path)[0]
     ini_path = path.join(project_path, 'pyramid_analytics', ini_filename)
     parser = configparser.SafeConfigParser()
     parser.read(ini_path)
     return parser
Esempio n. 2
0
def init_amd_spec(config, cache_max_age=None):
    cfg = config.get_settings()
    if not cfg['amd.spec']:
        return

    if not cfg['amd.spec-dir']:
        raise ConfigurationError("amd.spec-dir is required.")

    directory = RESOLVER.resolve(cfg['amd.spec-dir']).abspath()

    # register static view
    config.add_static_view('_amdjs/bundles/', directory)

    specs = {}
    for spec, specfile in cfg['amd.spec']:
        if spec in specs:
            raise ConfigurationError("Spec '%s' already defined." % spec)

        specs[spec] = specfile

    spec_mods = {}

    for spec, specfile in specs.items():
        f = RESOLVER.resolve(specfile).abspath()

        parser = configparser.SafeConfigParser()
        parser.read(f)

        mods = {}
        for section in parser.sections():
            items = dict(parser.items(section))

            if section.endswith('.js'):
                modules = [
                    s for s in
                    [s.strip() for s in items.get('modules', '').split()]
                    if not s.startswith('#')]
                if modules:
                    md5 = hashlib.md5()
                    fpath = os.path.join(directory, section)
                    with open(fpath, 'rb') as f:
                        md5.update(f.read())

                    item = {'name': section,
                            'md5': md5.hexdigest(),
                            'path': fpath}

                mods[section] = item
                for mod in modules:
                    mods[mod] = item

        spec_mods[spec] = mods
        spec_mods['%s-init' % spec] = os.path.join(
            directory, 'init-%s.js' % spec)

    config.registry[ID_AMD_SPEC] = spec_mods
    config.registry[ID_AMD_SPEC_] = cache_max_age
Esempio n. 3
0
def app_name_from_ini_file(ini_file_path):
    """
    Returns the name of the main application from the given ini file. See
    :function:`app_name_from_ini_parser` for details.

    :param ini_file_path: Path to the .ini file to parse.
    """
    parser = configparser.SafeConfigParser()
    parser.read(ini_file_path)
    return app_name_from_ini_parser(parser)
Esempio n. 4
0
def init_settings(pconfig, cfg=None, section=configparser.DEFAULTSECT):
    """Initialize settings management system. This function available
    as pyramid configurator directive. You should call it during
    application configuration process.

    .. code-block:: python

      config = Configurator()
      config.include('ptah')

      # initialize ptah setting management system
      config.ptah_init_settings()

    """
    settings = config.get_cfg_storage(SETTINGS_OB_ID, pconfig.registry,
                                      Settings)

    if settings.initialized:
        raise RuntimeError(
            "initialize_settings has been called more than once.")

    log.info('Initializing ptah settings')

    settings.initialized = True

    if cfg is None:
        cfg = pconfig.registry.settings

    here = cfg.get('here', './')
    include = cfg.get('include', '')
    for f in include.split('\n'):
        f = f.strip()
        if f and os.path.exists(f):
            parser = configparser.SafeConfigParser()
            parser.read(f)
            if section == configparser.DEFAULTSECT or \
                    parser.has_section(section):
                cfg.update(parser.items(section, vars={'here': here}))

    pconfig.begin()
    try:
        settings.init(pconfig, cfg)
        pconfig.registry.notify(
            ptah.events.SettingsInitializing(pconfig, pconfig.registry))
        pconfig.registry.notify(
            ptah.events.SettingsInitialized(pconfig, pconfig.registry))
    except Exception as e:
        raise StopException(e)
    finally:
        pconfig.end()
Esempio n. 5
0
def init_settings(pconfig, cfg, section=configparser.DEFAULTSECT):
    """ initialize settings management system """
    registry = pconfig.registry
    settings = config.get_cfg_storage(SETTINGS_OB_ID, pconfig.registry,
                                      Settings)

    if settings.initialized:
        raise RuntimeError(
            "initialize_settings has been called more than once.")

    log.info('Initializing ptah settings')

    settings.initialized = True

    if cfg:
        here = cfg.get('here', './')

        include = cfg.get('include', '')
        for f in include.split('\n'):
            f = f.strip()
            if f and os.path.exists(f):
                parser = configparser.SafeConfigParser()
                parser.read(f)
                if section == configparser.DEFAULTSECT or \
                       parser.has_section(section):
                    cfg.update(parser.items(section, vars={'here': here}))

    pconfig.begin()
    try:
        settings.init(pconfig, cfg)
        pconfig.registry.notify(
            ptah.events.SettingsInitializing(pconfig, pconfig.registry))
        pconfig.registry.notify(
            ptah.events.SettingsInitialized(pconfig, pconfig.registry))
    except Exception as e:
        raise StopException(e)
    finally:
        pconfig.end()
Esempio n. 6
0
 def __init__(self,
              ini_file_path=None,
              app_name=None,
              package_name=None,
              config_file_name=None):
     self.__ini_file_path = ini_file_path
     self.__app_name = app_name
     self.__package_name = package_name
     self.__config_file_name = config_file_name
     self.__app_url = None
     self.__app_settings = None
     self.__default_settings = None
     self.__host = '0.0.0.0'
     self.__port = '6543'
     if not ini_file_path is None:
         self.__parser = self.__parsers.get(ini_file_path)
         if self.__parser is None:
             defaults = {'here': os.path.dirname(ini_file_path)}
             self.__parser = \
                 configparser.SafeConfigParser(defaults=defaults)
             self.__parsers[ini_file_path] = self.__parser
     else:
         self.__parser = None
Esempio n. 7
0
    def build_bundles(self):
        cfg = self.registry.settings

        node_path = cfg['amd.node']
        if not node_path:
            node_path = NODE_PATH

        if not node_path:
            print("Can't find nodejs")
            return

        if not cfg['amd.spec']:
            print("Spec files are not specified in .ini file")
            return

        if not cfg['amd.spec-dir']:
            print("Destination directory is not specified in .ini file")
            return

        storage = self.registry.get(ID_AMD_MODULE)
        if not storage:
            return

        resolver = self.resolver

        UGLIFY = resolver.resolve(
            'pyramid_amdjs:node_modules/uglify-js/bin/uglifyjs').abspath()

        specs = OrderedDict(cfg['amd.spec'])
        for spec, specfile in specs.items():
            print("\n\nProcessing: %s (%s)" % (spec, specfile))

            f = resolver.resolve(specfile).abspath()
            parser = configparser.SafeConfigParser()
            parser.read(f)

            # build init js
            text = build_init(self.request, spec)
            if text is not None:
                md5 = hashlib.md5()
                md5.update(text.encode('utf-8'))

                text = "var __file_hash__ = '||%s||';\n%s" % (md5.hexdigest(),
                                                              text)

                initpath = os.path.join(cfg['amd.spec-dir'],
                                        'init-%s.js' % spec)
                with open(initpath, 'w') as dest:
                    dest.write(text)

            # build js bundle
            bundles = []
            processed = []

            for section in parser.sections():
                if section.endswith('.js'):
                    items = dict(parser.items(section))
                    url = items.get('url', '')
                    modules = items.get('modules', '')
                    if not modules:
                        continue

                    modules = [
                        s for s in [s.strip() for s in modules.split()]
                        if not s.startswith('#') and s
                    ]
                    bundles.append((section, url, modules))

            tmp_storage = self.registry.get(ID_BUNDLE)

            for jsname, url, modules in bundles:
                js = []
                for module in modules:
                    if module in tmp_storage:
                        text = build_hb_bundle(module, tmp_storage[module],
                                               self.registry)
                        processed.append(module)
                        js.append((module, None, text))
                        continue

                    intr = storage.get(module)
                    if not intr:
                        print("Can't find module '%s'" % module)
                        continue

                    processed.append(module)
                    js.append((module, intr['path'],
                               resolver.resolve(intr['path']).abspath()))

                _, tpath = tempfile.mkstemp()

                print('')
                print(grpTitleWrap.fill(jsname))

                f = open(tpath, 'ab')
                for name, path, fpath in js:
                    print(
                        grpDescriptionWrap.fill(
                            '%s: %s' % (name, path or 'templates bundle')))

                    if path is None:
                        f.write(bytes_(fpath, 'utf8'))
                        f.write(bytes_(';\n', 'utf8'))
                    else:
                        with open(fpath, 'rb') as source:
                            f.write(source.read())
                            f.write(bytes_(';\n', 'utf8'))

                f.close()

                path = os.path.join(cfg['amd.spec-dir'], jsname)
                print('write to:', path)
                with open(path, 'wb') as dest:
                    if self.options.nomin:
                        dest.write(open(tpath, 'rb').read())
                    else:
                        js = check_output((NODE_PATH, UGLIFY, '-nc', tpath))
                        dest.write(js)

                os.unlink(tpath)

            notprocessed = []
            for name, path in storage.items():
                if name not in processed:
                    notprocessed.append((name, path))

            if spec in ('', 'main') and notprocessed:
                print("\n\nList of not processed modules:")
                for name, intr, in sorted(notprocessed):
                    print(
                        grpDescriptionWrap.fill('%s: %s' %
                                                (name, intr['path'])))
Esempio n. 8
0
 def __make_parser(cls):
     if not cls.ini_file_path is None:
         defaults = {'here': os.path.dirname(cls.ini_file_path)}
     else:
         defaults = {}
     return configparser.SafeConfigParser(defaults=defaults)
Esempio n. 9
0
    def __init__(self, app, **kwargs):
        self.celery_conf = kwargs.pop('ini_file')
        self.parser = configparser.SafeConfigParser()
        self.parser.optionxform = str

        super(INILoader, self).__init__(app, **kwargs)