Exemplo n.º 1
0
 def _fix_paths(self, options):
     """
     fix `static_path` and `template_path` to be absolute
     path according to self.root_path so that PWD can be ignoreed.
     """
     for k in ('template_path', 'static_path'):
         if k in options:
             v = options.pop(k)
             if not os.path.isabs(v):
                 v = os.path.abspath(os.path.join(self.root_path, v))
                 app_log.debug('Fix %s to be absolute: %s' % (k, v))
             options[k] = v
Exemplo n.º 2
0
Arquivo: app.py Projeto: xoxoj/torext
 def _fix_paths(self, options):
     """
     fix `static_path` and `template_path` to be absolute
     path according to self.root_path so that PWD can be ignoreed.
     """
     for k in ('template_path', 'static_path'):
         if k in options:
             v = options.pop(k)
             if not os.path.isabs(v):
                 v = os.path.abspath(
                     os.path.join(self.root_path, v))
                 app_log.debug('Fix %s to be absolute: %s' % (k, v))
             options[k] = v
Exemplo n.º 3
0
    def command_line_config(self):
        """
        settings.py is the basis

        if wants to change them by command line arguments,
        the existing option will be transformed to the value type in settings.py
        the unexisting option will be treated as string by default,
        and transform to certain type if `!<type>` was added after the value.

        example:
        $ python app.py --PORT=1000

        NOTE This method is deprecated, use `torext.script` to parse command line arguments instead.
        """

        args = sys.argv[1:]
        args_dict = {}
        existed_keys = []
        new_keys = []

        for t in args:
            if not t.startswith('--'):
                raise errors.ArgsParseError('Bad arg: %s' % t)
            try:
                key, value = tuple(t[2:].split('='))
            except:
                raise errors.ArgsParseError('Bad arg: %s' % t)

            args_dict[key] = value

            if key in settings:
                existed_keys.append(key)
            else:
                new_keys.append(key)

        if existed_keys:
            app_log.debug('Changed settings:')
            for i in existed_keys:
                before = settings[i]
                type_ = type(before)
                if type_ is bool:
                    if args_dict[i] == 'True':
                        _value = True
                    elif args_dict[i] == 'False':
                        _value = False
                    else:
                        raise errors.ArgsParseError('%s should only be True or False' % i)
                else:
                    _value = type_(args_dict[i])
                settings[i] = _value
                app_log.debug('  %s  [%s]%s (%s)', i, type(settings[i]), settings[i], before)

        if new_keys:
            app_log.debug('New settings:')
            for i in new_keys:
                settings[i] = args_dict[i]
                app_log.debug('  %s  %s', i, args_dict[i])

        # NOTE if ``command_line_config`` is called, logging must be re-configed
        self.update_settings({})
Exemplo n.º 4
0
Arquivo: app.py Projeto: xoxoj/torext
    def command_line_config(self):
        """
        settings.py is the basis

        if wants to change them by command line arguments,
        the existing option will be transformed to the value type in settings.py
        the unexisting option will be treated as string by default,
        and transform to certain type if `!<type>` was added after the value.

        example:
        $ python app.py --PORT=1000

        NOTE This method is deprecated, use `torext.script` to parse command line arguments instead.
        """

        args = sys.argv[1:]
        args_dict = {}
        existed_keys = []
        new_keys = []

        for t in args:
            if not t.startswith('--'):
                raise errors.ArgsParseError('Bad arg: %s' % t)
            try:
                key, value = tuple(t[2:].split('='))
            except:
                raise errors.ArgsParseError('Bad arg: %s' % t)

            args_dict[key] = value

            if key in settings:
                existed_keys.append(key)
            else:
                new_keys.append(key)

        if existed_keys:
            app_log.debug('Changed settings:')
            for i in existed_keys:
                before = settings[i]
                type_ = type(before)
                if type_ is bool:
                    if args_dict[i] == 'True':
                        _value = True
                    elif args_dict[i] == 'False':
                        _value = False
                    else:
                        raise errors.ArgsParseError('%s should only be True or False' % i)
                else:
                    _value = type_(args_dict[i])
                settings[i] = _value
                app_log.debug('  %s  [%s]%s (%s)', i, type(settings[i]), settings[i], before)

        if new_keys:
            app_log.debug('New settings:')
            for i in new_keys:
                settings[i] = args_dict[i]
                app_log.debug('  %s  %s', i, args_dict[i])

        # NOTE if ``command_line_config`` is called, logging must be re-configed
        self.update_settings({})
Exemplo n.º 5
0
    def get_handlers(self):
        module = __import__(self.import_path, fromlist=[settings['PROJECT']])

        try:
            self._handlers = getattr(module, 'handlers')
        except AttributeError as e:
            # TODO enhanced traceback
            raise URLRouteError('Caught error when router was getting handlers from module: %s' % e)

        app_log.debug('got handlers from module %s' % self.import_path)

        for i in self._handlers:
            if isinstance(i[1], ModuleSearcher):
                raise URLRouteError('You should not use `include` in subapp handlers')

        return self._handlers
Exemplo n.º 6
0
Arquivo: app.py Projeto: reorx/torext
    def make_application(self, application_class=Application):
        options = self.get_application_options()
        app_log.debug('%s settings: %s', application_class.__name__, options)

        # this method intended to be able to called for multiple times,
        # so attributes should not be changed, just make a copy
        host_handlers = copy.copy(self.host_handlers)
        top_host_handlers = host_handlers.pop('.*$')
        application = application_class(top_host_handlers, **options)

        if host_handlers:
            for host, handlers in host_handlers.items():
                application.add_handlers(host, handlers)

        # call `application_configurator` to do extra setups
        self.application_configurator(application)
        return application
Exemplo n.º 7
0
Arquivo: app.py Projeto: xoxoj/torext
    def _make_application(self, application_class=Application):
        options = self.get_application_options()
        app_log.debug('%s settings: %s', application_class.__name__, options)

        # this method intended to be able to called for multiple times,
        # so attributes should not be changed, just make a copy
        host_handlers = copy.copy(self.host_handlers)
        top_host_handlers = host_handlers.pop('.*$')
        application = application_class(top_host_handlers, **options)

        if host_handlers:
            for host, handlers in host_handlers.iteritems():
                application.add_handlers(host, handlers)

        # call `application_configurator` to do extra setups
        self.application_configurator(application)
        return application
Exemplo n.º 8
0
Arquivo: app.py Projeto: reorx/torext
    def setup(self):
        """This function will be called both before `run` and testing started.
        """
        testing = settings.get('TESTING')

        if testing:
            # Fix nose handler in testing situation.
            config = settings['LOGGERS'].get('', {})
            set_nose_formatter(config)
            #print('testing, set nose formatter: {}'.format(config))

        # reset timezone
        os.environ['TZ'] = settings['TIME_ZONE']
        time.tzset()

        # determine project name
        if settings._module:
            project = os.path.split(self.root_path)[1]
            if settings['PROJECT']:
                assert settings['PROJECT'] == project, 'PROJECT specialized in settings (%s) '\
                    'should be the same as project directory name (%s)' % (settings['PROJECT'], project)
            else:
                settings['PROJECT'] = project

        # PROJECT should be importable as a python module
        if settings['PROJECT']:
            # add upper directory path to sys.path if not in
            if settings._module:
                _abs = os.path.abspath
                parent_path = os.path.dirname(self.root_path)
                if not _abs(parent_path) in [_abs(i) for i in sys.path]:
                    sys.path.insert(0, parent_path)
                    app_log.info('Add %s to sys.path' % _abs(parent_path))
            try:
                __import__(settings['PROJECT'])
                app_log.debug('import package `%s` success' %
                              settings['PROJECT'])
            except ImportError:
                raise ImportError(
                    'PROJECT could not be imported, may be app.py is outside the project'
                    'or there is no __init__ in the package.')

        self.is_setuped = True
Exemplo n.º 9
0
    def get_handlers(self):
        module = __import__(self.import_path, fromlist=[settings['PROJECT']])

        try:
            self._handlers = getattr(module, 'handlers')
        except AttributeError as e:
            # TODO enhanced traceback
            raise URLRouteError(
                'Caught error when router was getting handlers from module: %s'
                % e)

        app_log.debug('got handlers from module %s' % self.import_path)

        for i in self._handlers:
            if isinstance(i[1], ModuleSearcher):
                raise URLRouteError(
                    'You should not use `include` in subapp handlers')

        return self._handlers
Exemplo n.º 10
0
    def module_config(self, settings_module):
        """
        Optional function
        """
        assert hasattr(settings_module, '__file__'), 'settings must be a module'
        # set root_path according to module file
        self.set_root_path(settings_module=settings_module)
        app_log.debug('Set root_path: %s', self.root_path)

        global settings

        self.update_settings(dict(
            [(i, getattr(settings_module, i)) for i in dir(settings_module)
             if not i.startswith('_') and i == i.upper()]))

        settings._module = settings_module

        # keep a mapping to app on settings object
        settings._app = self
Exemplo n.º 11
0
Arquivo: app.py Projeto: xoxoj/torext
    def module_config(self, settings_module):
        """
        Optional function
        """
        assert hasattr(settings_module, '__file__'), 'settings must be a module'
        # set root_path according to module file
        self.set_root_path(settings_module=settings_module)
        app_log.debug('Set root_path: %s', self.root_path)

        global settings

        self.update_settings(dict(
            [(i, getattr(settings_module, i)) for i in dir(settings_module)
             if not i.startswith('_') and i == i.upper()]))

        settings._module = settings_module

        # keep a mapping to app on settings object
        settings._app = self
Exemplo n.º 12
0
Arquivo: app.py Projeto: xoxoj/torext
    def setup(self):
        """This function will be called both before `run` and testing started.
        """
        testing = settings.get('TESTING')

        if testing:
            # Fix nose handler in testing situation.
            config = settings['LOGGERS'].get('', {})
            set_nose_formatter(config)
            print 'testing, set nose formatter: %s' % config

        # reset timezone
        os.environ['TZ'] = settings['TIME_ZONE']
        time.tzset()

        # determine project name
        if settings._module:
            project = os.path.split(self.root_path)[1]
            if settings['PROJECT']:
                assert settings['PROJECT'] == project, 'PROJECT specialized in settings (%s) '\
                    'should be the same as project directory name (%s)' % (settings['PROJECT'], project)
            else:
                settings['PROJECT'] = project

        # PROJECT should be importable as a python module
        if settings['PROJECT']:
            # add upper directory path to sys.path if not in
            if settings._module:
                _abs = os.path.abspath
                parent_path = os.path.dirname(self.root_path)
                if not _abs(parent_path) in [_abs(i) for i in sys.path]:
                    sys.path.insert(0, parent_path)
                    app_log.info('Add %s to sys.path' % _abs(parent_path))
            try:
                __import__(settings['PROJECT'])
                app_log.debug('import package `%s` success' % settings['PROJECT'])
            except ImportError:
                raise ImportError('PROJECT could not be imported, may be app.py is outside the project'
                                  'or there is no __init__ in the package.')

        self.is_setuped = True
Exemplo n.º 13
0
class ModuleSearcher(object):
    def __init__(self, label):
        assert settings['PROJECT'], 'you must set PROJECT first'
        self.import_path = settings['PROJECT'] + '.' + label
        self._handlers = []

    def get_handlers(self):
        module = __import__(self.import_path, fromlist=[settings['PROJECT']])

        try:
            self._handlers = getattr(module, 'handlers')
        except AttributeError, e:
            # TODO enhanced traceback
            raise URLRouteError('Caught error when router was getting handlers from module: %s' % e)

        app_log.debug('got handlers from module %s' % self.import_path)

        for i in self._handlers:
            if isinstance(i[1], ModuleSearcher):
                raise URLRouteError('You should not use `include` in subapp handlers')

        return self._handlers
Exemplo n.º 14
0
 def add(self, spec):
     if self.prefix:
         spec = (self.prefix + spec[0], spec[1])
     app_log.debug('add url spec in router: %s' % str(spec))
     self._handlers.append(spec)