Beispiel #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
Beispiel #2
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
Beispiel #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({})
Beispiel #4
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({})
Beispiel #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
Beispiel #6
0
    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
Beispiel #7
0
    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
Beispiel #8
0
    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
Beispiel #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
Beispiel #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
Beispiel #11
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
Beispiel #12
0
    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
Beispiel #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
Beispiel #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)