Esempio n. 1
0
    def process_error(self, ex, action_name, pos_args, named_args):
        """
        arguments:
        ex -- a risen exception
        action_name -- a name of the original processed method
        pos_args -- positional arguments of the action method
        named_args -- key=>value arguments of the action method
        """
        e2 = self._analyze_error(ex)
        if not isinstance(e2, UserActionException):
            logging.getLogger(__name__).error(''.join(get_traceback()))

        return_type = self._get_method_metadata(action_name, 'return_type')
        if return_type == 'json':
            if settings.is_debug_mode() or type(ex) is UserActionException:
                json_msg = str(e2).decode('utf-8')
            else:
                json_msg = _('Failed to process your request. '
                             'Please try again later or contact system support.')
            return action_name, None, {'error': json_msg, 'contains_errors': True,
                                       'error_code': getattr(ex, 'error_code', None),
                                       'error_args': getattr(ex, 'error_args', {})}
        else:
            if not self._exceptmethod and self.is_template(action_name + '_form'):
                self._exceptmethod = action_name + '_form'
            if not self._exceptmethod:  # let general error handlers in run() handle the error
                raise e2
            else:
                self.add_system_message('error', e2.message)

            self._pre_dispatch(self._exceptmethod, None, named_args,
                               self._get_method_metadata(self._exceptmethod))
            em, self._exceptmethod = self._exceptmethod, None
            return self.process_method(em, pos_args, named_args)
Esempio n. 2
0
def setup_logger(log_path=None, logger_name=None, logging_level=None):
    """
    Configures logging (= module's logger variable).

    arguments:
    log_path -- path to a file where log will be written; if omitted then stdout is used
    logger_name -- a name to be used for logger (by default it is 'kontext_script')
    """
    if logger_name is not None:
        logger.name = logger_name

    if log_path is not None:
        handler = logging.handlers.RotatingFileHandler(
            log_path,
            maxBytes=DEFAULT_LOG_FILE_SIZE,
            backupCount=DEFAULT_NUM_LOG_FILES)
    else:
        handler = logging.StreamHandler(DEFAULT_LOG_OUT)
    handler.setFormatter(
        logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
    logger.addHandler(handler)
    if logging_level is None:
        logging_level = logging.INFO if not settings.is_debug_mode(
        ) else logging.DEBUG
    logger.setLevel(logging_level)
Esempio n. 3
0
    def process_method(self, methodname, request, pos_args, named_args):
        """
        This method handles mapping between HTTP actions and Controller's methods.
        The method expects 'methodname' argument to be a valid @exposed method.

        Please note that 'request' and 'pos_args'+'named_args' are used in a mutually exclusive
        way (the former is passed to 'new style' actions, the latter is used for legacy ones).

        returns: tuple of 3 elements
          0 = method name actually used (it may have changed e.g. due to an error)
          1 = template name
          2 = template data dict
        """
        reload = {'headers': 'wordlist_form'}
        # reload parameter returns user from a result page
        # to a respective form preceding the result (by convention,
        # this is usually encoded as [action] -> [action]_form
        action_metadata = self._get_method_metadata(methodname)
        if getattr(self.args, 'reload', None):
            self.args.reload = None
            if methodname != 'subcorp':
                reload_template = reload.get(methodname, methodname + '_form')
                if self.is_template(reload_template):
                    return self.process_method(reload_template, request, pos_args, named_args)
        method = getattr(self, methodname)
        try:
            default_tpl_path = '%s/%s.tmpl' % (self.get_mapping_url_prefix()[1:], methodname)
            if not action_metadata.get('legacy', False):
                # new-style actions use werkzeug.wrappers.Request
                args = [request] + self._args_mappings.values()
                method_ans = apply(method, args)
            else:
                method_ans = self._invoke_legacy_action(method, pos_args, named_args)
            return methodname, getattr(method, 'template', default_tpl_path), method_ans
        except Exception as e:
            e2 = self._analyze_error(e)
            if not isinstance(e2, UserActionException):
                logging.getLogger(__name__).error(''.join(get_traceback()))

            return_type = self._get_method_metadata(methodname, 'return_type')
            if return_type == 'json':
                if settings.is_debug_mode() or type(e) is UserActionException:
                    json_msg = str(e).decode('utf-8')
                else:
                    json_msg = _('Failed to process your request. '
                                 'Please try again later or contact system support.')
                return methodname, None, {'error': json_msg, 'contains_errors': True}
            else:
                if not self._exceptmethod and self.is_template(methodname + '_form'):
                    self._exceptmethod = methodname + '_form'
                if not self._exceptmethod:  # let general error handlers in run() handle the error
                    raise e2
                else:
                    self.add_system_message('error', e2.message)

                self._pre_dispatch(self._exceptmethod, None, named_args,
                                   self._get_method_metadata(self._exceptmethod))
                em, self._exceptmethod = self._exceptmethod, None
                return self.process_method(em, request, pos_args, named_args)
Esempio n. 4
0
    def run(self, path=None):
        """
        This method wraps all the processing of an HTTP request.

        arguments:
        path -- path part of URL

        returns:
        a 4-tuple: HTTP status, HTTP headers, valid SID flag, response body
        """
        self._install_plugin_actions()
        self._proc_time = time.time()
        path = path if path is not None else self._import_req_path()
        named_args = {}
        headers = []
        action_metadata = self._get_method_metadata(path[0])
        try:
            self.init_session()
            if self.is_action(path[0], action_metadata):
                path, named_args = self.pre_dispatch(path, named_args, action_metadata)
                self._pre_action_validate()
                methodname, tmpl, result = self.process_action(path[0], path, named_args)
            else:
                raise NotFoundException(_('Unknown action [%s]') % path[0])
        except UserActionException as ex:
            self._status = ex.code
            self.add_system_message('error', fetch_exception_msg(ex))
            methodname, tmpl, result = self.process_action('message', path, named_args)
        except Exception as ex:
            # an error outside the action itself (i.e. pre_dispatch, action validation,
            # post_dispatch etc.)
            logging.getLogger(__name__).error(u'%s\n%s' % (ex, ''.join(get_traceback())))
            if settings.is_debug_mode():
                self._status = 500
                self.add_system_message('error', fetch_exception_msg(ex))
            else:
                self.handle_dispatch_error(ex)
            methodname, tmpl, result = self.process_action('message', path, named_args)

        # Let's test whether process_method actually invoked requested method.
        # If not (e.g. there was an error and a fallback has been used) then reload action metadata
        if methodname != path[0]:
            action_metadata = self._get_method_metadata(methodname)

        self._proc_time = round(time.time() - self._proc_time, 4)
        self.post_dispatch(methodname, action_metadata, tmpl, result)
        # response rendering
        headers += self.output_headers(action_metadata.get('return_type', 'html'))
        output = StringIO.StringIO()
        if self._status < 300 or self._status >= 400:
            self.output_result(methodname, tmpl, result, action_metadata, outf=output)
        ans_body = output.getvalue()
        output.close()
        return self._export_status(), headers, self._uses_valid_sid, ans_body
Esempio n. 5
0
def setup_logger(conf):
    """
    Sets up file-based rotating logger. All the parameters are extracted
    from conf argument:
    path: /kontext/global/log_path
    maximum file size (optional, default is 8MB): /kontext/global/log_file_size
    number of backed-up files (optional, default is 10): /kontext/global/log_num_files
    """
    handler = handlers.RotatingFileHandler(conf.get('logging', 'path'),
                                           maxBytes=conf.get_int('logging', 'file_size', 8000000),
                                           backupCount=conf.get_int('logging', 'num_files', 10))
    handler.setFormatter(logging.Formatter(fmt='%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(logging.INFO if not settings.is_debug_mode() else logging.DEBUG)
Esempio n. 6
0
 def _create_user_action_err_result(self, ex, return_type):
     """
     arguments:
     ex -- a risen exception
     return_type --
     """
     e2 = self._normalize_error(ex)
     if settings.is_debug_mode() or isinstance(e2, UserActionException):
         user_msg = fetch_exception_msg(e2)
     else:
         user_msg = translate('Failed to process your request. '
                              'Please try again later or contact system support.')
     if return_type == 'json':
         return dict(error_code=getattr(ex, 'error_code', None),
                     error_args=getattr(ex, 'error_args', {}))
     else:
         return dict()
Esempio n. 7
0
 def _create_user_action_err_result(self, ex: Exception, return_type: str) -> Dict[str, Any]:
     """
     arguments:
     ex -- a risen exception
     return_type --
     """
     e2 = self._normalize_error(ex)
     if settings.is_debug_mode() or isinstance(e2, UserActionException):
         user_msg = fetch_exception_msg(e2)
     else:
         user_msg = translate('Failed to process your request. '
                              'Please try again later or contact system support.')
     if return_type == 'json':
         return dict(error_code=getattr(ex, 'error_code', None),
                     error_args=getattr(ex, 'error_args', {}))
     else:
         return dict()
Esempio n. 8
0
 def setup_logger(conf):
     """
     Sets up file-based rotating logger. All the parameters are extracted
     from conf argument:
     path: /kontext/global/log_path
     maximum file size (optional, default is 8MB): /kontext/global/log_file_size
     number of backed-up files (optional, default is 10): /kontext/global/log_num_files
     """
     handler = handlers.RotatingFileHandler(
         conf.get('logging', 'path'),
         maxBytes=conf.get_int('logging', 'file_size', 8000000),
         backupCount=conf.get_int('logging', 'num_files', 10))
     handler.setFormatter(
         logging.Formatter(
             fmt='%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
     logger.addHandler(handler)
     logger.setLevel(
         logging.INFO if not settings.is_debug_mode() else logging.DEBUG)
Esempio n. 9
0
    def handle_action_error(self, ex, action_name, pos_args, named_args):
        """
        arguments:
        ex -- a risen exception
        action_name -- a name of the original processed method
        pos_args -- positional arguments of the action method
        named_args -- key=>value arguments of the action method
        """
        e2 = self._normalize_error(ex)
        if not isinstance(e2, UserActionException):
            logging.getLogger(__name__).error(''.join(get_traceback()))
            self._status = 500
        else:
            self._status = getattr(e2, 'code', 500)
        if settings.is_debug_mode() or isinstance(e2, UserActionException):
            user_msg = e2.message if type(e2.message) is unicode else str(e2).decode('utf-8')
        else:
            user_msg = _('Failed to process your request. '
                         'Please try again later or contact system support.')
        return_type = self._get_method_metadata(action_name, 'return_type')
        if return_type == 'json':
            return (
                action_name,
                None,
                dict(messages=[user_msg],
                     error_code=getattr(ex, 'error_code', None),
                     error_args=getattr(ex, 'error_args', {}))
            )
        else:
            if not self._exceptmethod and self._is_template(action_name + '_form'):
                self._exceptmethod = action_name + '_form'
            if not self._exceptmethod:  # let general error handlers in run() handle the error
                raise e2
            else:
                self.add_system_message('error', user_msg)

            self.pre_dispatch(self._exceptmethod, named_args,
                              self._get_method_metadata(self._exceptmethod))
            em, self._exceptmethod = self._exceptmethod, None
            return self.process_action(em, pos_args, named_args)
Esempio n. 10
0
def setup_logger(log_path=None, logger_name=None, logging_level=None):
    """
    Configures logging (= module's logger variable).

    arguments:
    log_path -- path to a file where log will be written; if omitted then stdout is used
    logger_name -- a name to be used for logger (by default it is 'kontext_script')
    """
    if logger_name is not None:
        logger.name = logger_name

    if log_path is not None:
        handler = logging.handlers.RotatingFileHandler(log_path,
                                                       maxBytes=DEFAULT_LOG_FILE_SIZE,
                                                       backupCount=DEFAULT_NUM_LOG_FILES)
    else:
        handler = logging.StreamHandler(DEFAULT_LOG_OUT)
    handler.setFormatter(logging.Formatter('%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
    logger.addHandler(handler)
    if logging_level is None:
        logging_level = logging.INFO if not settings.is_debug_mode() else logging.DEBUG
    logger.setLevel(logging_level)
Esempio n. 11
0
    def handle_action_error(self, ex, action_name, pos_args, named_args):
        """
        arguments:
        ex -- a risen exception
        action_name -- a name of the original processed method
        pos_args -- positional arguments of the action method
        named_args -- key=>value arguments of the action method
        """
        e2 = self._normalize_error(ex)
        if not isinstance(e2, UserActionException):
            logging.getLogger(__name__).error(''.join(get_traceback()))
            self._status = 500
        else:
            self._status = getattr(e2, 'code', 500)
        if settings.is_debug_mode() or isinstance(e2, UserActionException):
            user_msg = e2.message if type(
                e2.message) is unicode else str(e2).decode('utf-8')
        else:
            user_msg = _('Failed to process your request. '
                         'Please try again later or contact system support.')
        return_type = self._get_method_metadata(action_name, 'return_type')
        if return_type == 'json':
            return (action_name, None,
                    dict(messages=[user_msg],
                         error_code=getattr(ex, 'error_code', None),
                         error_args=getattr(ex, 'error_args', {})))
        else:
            if not self._exceptmethod and self._is_template(action_name +
                                                            '_form'):
                self._exceptmethod = action_name + '_form'
            if not self._exceptmethod:  # let general error handlers in run() handle the error
                raise e2
            else:
                self.add_system_message('error', user_msg)

            self.pre_dispatch(self._exceptmethod, named_args,
                              self._get_method_metadata(self._exceptmethod))
            em, self._exceptmethod = self._exceptmethod, None
            return self.process_action(em, pos_args, named_args)
Esempio n. 12
0
    def setup_logger(conf):
        """
        Sets up file-based rotating logger based on XML config.xml.
        """
        if conf.contains('logging', 'stderr'):
            handler = logging.StreamHandler(sys.stderr)
        elif conf.contains('logging', 'stdout'):
            handler = logging.StreamHandler(sys.stdout)
        else:
            try:
                from concurrent_log_handler import ConcurrentRotatingFileHandler as HandlerClass
            except ImportError:
                from logging.handlers import RotatingFileHandler as HandlerClass
            handler = HandlerClass(
                conf.get('logging', 'path').format(pid=os.getpid()),
                maxBytes=conf.get_int('logging', 'file_size', 8000000),
                backupCount=conf.get_int('logging', 'num_files', 10))

        handler.setFormatter(
            logging.Formatter(
                fmt='%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
        logger.addHandler(handler)
        logger.setLevel(
            logging.INFO if not settings.is_debug_mode() else logging.DEBUG)
Esempio n. 13
0
    def run(self, path=None):
        """
        This method wraps all the processing of an HTTP request.

        arguments:
        path -- path part of URL

        returns:
        a 4-tuple: HTTP status, HTTP headers, valid SID flag, response body
        """
        self._install_plugin_actions()
        self._proc_time = time.time()
        path = path if path is not None else self._import_req_path()
        methodname = path[0]
        named_args = {}
        headers = []
        action_metadata = self._get_method_metadata(methodname)
        if not action_metadata:

            def null():
                pass

            action_metadata = {}
            action_metadata.update(exposed()(null).__dict__)
        return_type = action_metadata['return_type']
        try:
            self.init_session()
            if self.is_action(methodname, action_metadata):
                named_args = self.pre_dispatch(methodname, named_args,
                                               action_metadata)
                self._pre_action_validate()
                tmpl, result = self.process_action(methodname, named_args)
            else:
                orig_method = methodname
                methodname = 'message'
                raise NotFoundException(
                    translate('Unknown action [%s]') % orig_method)
        except CorpusForbiddenException as ex:
            self._status = ex.code
            tmpl, result = self._run_message_action(named_args,
                                                    action_metadata, 'error',
                                                    ex.message)
        except UserActionException as ex:
            self._status = ex.code
            msg_args = self._create_user_action_err_result(ex, return_type)
            named_args.update(msg_args)
            tmpl, result = self._run_message_action(named_args,
                                                    action_metadata, 'error',
                                                    ex.message)
        except werkzeug.exceptions.BadRequest as ex:
            self._status = ex.code
            tmpl, result = self._run_message_action(
                named_args, action_metadata, 'error',
                '{0}: {1}'.format(ex.name, ex.description))
        except Exception as ex:
            # an error outside the action itself (i.e. pre_dispatch, action validation,
            # post_dispatch etc.)
            logging.getLogger(__name__).error(u'%s\n%s' %
                                              (ex, ''.join(get_traceback())))
            self._status = 500
            if settings.is_debug_mode():
                message = fetch_exception_msg(ex)
            else:
                message = translate(
                    'Failed to process your request. Please try again later or contact system support.'
                )
            tmpl, result = self._run_message_action(named_args,
                                                    action_metadata, 'error',
                                                    message)

        self._proc_time = round(time.time() - self._proc_time, 4)
        self.post_dispatch(methodname, action_metadata, tmpl, result)
        # response rendering
        headers += self.output_headers(return_type)
        output = StringIO.StringIO()
        if self._status < 300 or self._status >= 400:
            self.output_result(methodname,
                               tmpl,
                               result,
                               action_metadata,
                               outf=output)
        ans_body = output.getvalue()
        output.close()
        return self._export_status(), headers, self._uses_valid_sid, ans_body
Esempio n. 14
0
    def run(
        self,
        path: Optional[List[str]] = None
    ) -> Tuple[str, List[Tuple[str, str]], bool, Union[str, bytes]]:
        """
        This method wraps all the processing of an HTTP request.

        arguments:
        path -- path part of URL

        returns:
        a 4-tuple: HTTP status, HTTP headers, valid SID flag, response body
        """
        self._install_plugin_actions()
        self._proc_time = time.time()
        path = path if path is not None else self._import_req_path()
        methodname = path[0]
        err: Optional[Tuple[Exception, Optional[str]]] = None
        action_metadata: Dict[str, Any] = self._get_method_metadata(methodname)

        tmpl: Optional[str]
        result: Optional[Dict[str, Any]]
        if not action_metadata:

            def null():
                pass

            action_metadata = {}
            action_metadata.update(exposed()(null).__dict__)
        try:
            self.init_session()
            if self.is_action(methodname, action_metadata):
                req_args = self.pre_dispatch(methodname, action_metadata)
                self._pre_action_validate()
                tmpl, result = self.process_action(methodname, req_args)
            else:
                orig_method = methodname
                methodname = 'message'
                raise NotFoundException(
                    translate('Unknown action [%s]') % orig_method)
        except CorpusForbiddenException as ex:
            err = (ex, None)
            self._response.set_http_status(ex.code)
            msg_args = self._create_err_action_args(
                ex, action_metadata['return_type'])
            tmpl, result = self._run_message_action(
                msg_args, action_metadata, 'error',
                repr(ex) if settings.is_debug_mode() else str(ex))
        except ImmediateRedirectException as ex:
            err = (ex, None)
            tmpl, result = None, None
            self.redirect(ex.url, ex.code)
        except UserActionException as ex:
            err = (ex, None)
            self._response.set_http_status(ex.code)
            msg_args = self._create_err_action_args(
                ex, action_metadata['return_type'])
            tmpl, result = self._run_message_action(
                msg_args, action_metadata, 'error',
                repr(ex) if settings.is_debug_mode() else str(ex))
        except werkzeug.exceptions.BadRequest as ex:
            err = (ex, None)
            self._response.set_http_status(ex.code)
            msg_args = self._create_err_action_args(
                ex, action_metadata['return_type'])
            tmpl, result = self._run_message_action(
                msg_args, action_metadata, 'error',
                '{0}: {1}'.format(ex.name, ex.description))
        except Exception as ex:
            # an error outside the action itself (i.e. pre_dispatch, action validation,
            # post_dispatch etc.)
            err_id = hashlib.sha1(str(
                uuid.uuid1()).encode('ascii')).hexdigest()
            err = (ex, err_id)
            logging.getLogger(__name__).error('{0}\n@{1}\n{2}'.format(
                ex, err_id, ''.join(get_traceback())))
            self._response.set_http_status(500)
            if settings.is_debug_mode():
                message = fetch_exception_msg(ex)
            else:
                message = translate(
                    'Failed to process your request. Please try again later or contact system support.'
                )
            msg_args = self._create_err_action_args(
                ex, action_metadata['return_type'])
            tmpl, result = self._run_message_action(msg_args, action_metadata,
                                                    'error', message)

        self._proc_time = round(time.time() - self._proc_time, 4)
        self.post_dispatch(methodname, action_metadata, tmpl, result, err)
        # response rendering
        headers = self._response.output_headers(action_metadata['return_type'])
        ans_body = self._response.output_result(
            method_name=methodname,
            template=tmpl,
            result=result,
            inject_page_globals=self.inject_globals,
            action_metadata=action_metadata,
            return_type=action_metadata['return_type'])
        return self._response.http_status, headers, self._uses_valid_sid, ans_body
Esempio n. 15
0
    def run(self, path=None, selectorname=None):
        """
        This method wraps all the processing of an HTTP request.

        arguments:
        path -- path part of URL
        selectorname -- ???

        returns:
        a 4-tuple: HTTP status, HTTP headers, valid SID flag, response body
        """
        self._install_plugin_actions()
        self._proc_time = time.time()
        path = path if path is not None else self.import_req_path()
        named_args = {}
        headers = []
        action_metadata = self._get_method_metadata(path[0])
        try:
            self._init_session()
            if self.is_action(path[0]) and self._method_is_exposed(action_metadata):
                path, selectorname, named_args = self._pre_dispatch(path, selectorname, named_args,
                                                                    action_metadata)
                self._pre_action_validate()
                methodname, tmpl, result = self.process_method(path[0], path, named_args)
            else:
                raise NotFoundException(_('Unknown action [%s]') % path[0])

        except AuthException as ex:
            self._status = 401
            self.add_system_message('error', u'%s' % fetch_exception_msg(ex))
            methodname, tmpl, result = self.process_method('message', path, named_args)

        except (UserActionException, RuntimeError) as ex:
            if hasattr(ex, 'code'):
                self._status = ex.code
            self.add_system_message('error', fetch_exception_msg(ex))
            methodname, tmpl, result = self.process_method('message', path, named_args)

        except Exception as ex:  # we assume that this means some kind of a fatal error
            self._status = 500
            logging.getLogger(__name__).error(u'%s\n%s' % (ex, ''.join(get_traceback())))
            if settings.is_debug_mode():
                self.add_system_message('error', fetch_exception_msg(ex))
            else:
                self.add_system_message('error',
                                        _('Failed to process your request. '
                                          'Please try again later or contact system support.'))
            methodname, tmpl, result = self.process_method('message', path, named_args)
        # Let's test whether process_method actually invoked requested method.
        # If not (e.g. there was an error and a fallback has been used) then reload action metadata
        if methodname != path[0]:
            action_metadata = self._get_method_metadata(methodname)

        self._proc_time = round(time.time() - self._proc_time, 4)
        self._post_dispatch(methodname, action_metadata, tmpl, result)

        # response rendering
        resp_time = time.time()
        headers += self.output_headers(action_metadata.get('return_type', 'html'))

        output = StringIO.StringIO()
        if self._status < 300 or self._status >= 400:
            self.output_result(methodname, tmpl, result, action_metadata, outf=output)
        ans_body = output.getvalue()
        output.close()
        logging.getLogger(__name__).debug('template rendering time: %s' % (round(time.time() - resp_time, 4),))
        return self._export_status(), headers, self._uses_valid_sid, ans_body
Esempio n. 16
0
    def run(self, path=None):
        """
        This method wraps all the processing of an HTTP request.

        arguments:
        path -- path part of URL

        returns:
        a 4-tuple: HTTP status, HTTP headers, valid SID flag, response body
        """
        self._install_plugin_actions()
        self._proc_time = time.time()
        path = path if path is not None else self._import_req_path()
        methodname = path[0]
        named_args = {}
        headers = []
        action_metadata = self._get_method_metadata(methodname)
        if not action_metadata:
            def null(): pass
            action_metadata = {}
            action_metadata.update(exposed()(null).__dict__)
        try:
            self.init_session()
            if self.is_action(methodname, action_metadata):
                named_args = self.pre_dispatch(methodname, named_args, action_metadata)
                self._pre_action_validate()
                tmpl, result = self.process_action(methodname, named_args)
            else:
                orig_method = methodname
                methodname = 'message'
                raise NotFoundException(translate('Unknown action [%s]') % orig_method)
        except CorpusForbiddenException as ex:
            self._status = ex.code
            tmpl, result = self._run_message_action(
                named_args, action_metadata, 'error', ex.message)
        except ImmediateRedirectException as ex:
            tmpl, result = None, None
            self.redirect(ex.url, ex.code)
        except UserActionException as ex:
            self._status = ex.code
            msg_args = self._create_user_action_err_result(ex, action_metadata['return_type'])
            tmpl, result = self._run_message_action(
                msg_args, action_metadata, 'error', ex.message)
        except werkzeug.exceptions.BadRequest as ex:
            self._status = ex.code
            tmpl, result = self._run_message_action(named_args, action_metadata,
                                                    'error', '{0}: {1}'.format(ex.name, ex.description))
        except Exception as ex:
            # an error outside the action itself (i.e. pre_dispatch, action validation,
            # post_dispatch etc.)
            logging.getLogger(__name__).error(u'%s\n%s' % (ex, ''.join(get_traceback())))
            self._status = 500
            if settings.is_debug_mode():
                message = fetch_exception_msg(ex)
            else:
                message = translate(
                    'Failed to process your request. Please try again later or contact system support.')
            tmpl, result = self._run_message_action(named_args, action_metadata, 'error', message)

        self._proc_time = round(time.time() - self._proc_time, 4)
        self.post_dispatch(methodname, action_metadata, tmpl, result)
        # response rendering
        headers += self.output_headers(action_metadata['return_type'])
        output = StringIO.StringIO()
        if self._status < 300 or self._status >= 400:
            self.output_result(methodname, tmpl, result, action_metadata,
                               return_type=action_metadata['return_type'], outf=output)
        ans_body = output.getvalue()
        output.close()
        return self._export_status(), headers, self._uses_valid_sid, ans_body
Esempio n. 17
0
if settings.get('global', 'umask', None):
    os.umask(int(settings.get('global', 'umask'), 8))

if not settings.get_bool('global', 'maintenance'):
    application = KonTextWsgiApp()
else:
    application = MaintenanceWsgiApp()

robots_path = os.path.join(os.path.dirname(__file__), 'files/robots.txt')
if os.path.isfile(robots_path):
    from werkzeug.wsgi import SharedDataMiddleware
    application = SharedDataMiddleware(application, {
        '/robots.txt': robots_path
    })

if settings.is_debug_mode():
    from werkzeug.debug import DebuggedApplication
    application = DebuggedApplication(application)
    # profiling
    if settings.debug_level() == settings.DEBUG_AND_PROFILE:
        from werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream
        stream = MergeStream(sys.stdout, open(settings.get('global', 'profile_log_path'), 'w'))
        application = ProfilerMiddleware(application, stream)


if __name__ == '__main__':
    from werkzeug.serving import run_simple
    from werkzeug.wsgi import SharedDataMiddleware
    import argparse

    DEFAULT_PORT = 5000
Esempio n. 18
0
if __name__ == "__main__":
    with Connection(redis.Redis(
        host=settings.get('calc_backend', 'rq_redis_host'),
        port=settings.get('calc_backend', 'rq_redis_port'),
        db=settings.get('calc_backend', 'rq_redis_db')
    )):

        logging_handlers = []
        if settings.contains('logging', 'stderr'):
            handler = logging.StreamHandler(sys.stderr)
        elif settings.contains('logging', 'stdout'):
            handler = logging.StreamHandler(sys.stdout)
        elif settings.contains('calc_backend', 'rq_log_path'):
            handler = logging.FileHandler(settings.get('calc_backend', 'rq_log_path'))

        if handler:
            handler.setFormatter(logging.Formatter(
                fmt='%(asctime)s [%(name)s] %(levelname)s: %(message)s'))
            logging_handlers.append(handler)

        logging.basicConfig(
            handlers=logging_handlers,
            level=logging.INFO if not settings.is_debug_mode() else logging.DEBUG
        )

        qs = sys.argv[1:] or ['default']
        worker.init_scheduler()
        w = Worker(qs)
        w.work()
Esempio n. 19
0
# please note that some environments may provide umask setting themselves
if settings.get('global', 'umask', None):
    os.umask(int(settings.get('global', 'umask'), 8))

if not settings.get_bool('global', 'maintenance'):
    application = KonTextWsgiApp()
else:
    application = MaintenanceWsgiApp()

robots_path = os.path.join(os.path.dirname(__file__), 'files/robots.txt')
if os.path.isfile(robots_path):
    from werkzeug.wsgi import SharedDataMiddleware
    application = SharedDataMiddleware(application,
                                       {'/robots.txt': robots_path})

if settings.is_debug_mode():
    from werkzeug.debug import DebuggedApplication
    application = DebuggedApplication(application)
    # profiling
    if settings.debug_level() == settings.DEBUG_AND_PROFILE:
        from werkzeug.contrib.profiler import ProfilerMiddleware, MergeStream
        stream = MergeStream(
            sys.stdout, open(settings.get('global', 'profile_log_path'), 'w'))
        application = ProfilerMiddleware(application, stream)

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    from werkzeug.wsgi import SharedDataMiddleware
    import argparse

    DEFAULT_PORT = 5000
Esempio n. 20
0
    def run(self, path=None):
        """
        This method wraps all the processing of an HTTP request.

        arguments:
        path -- path part of URL

        returns:
        a 4-tuple: HTTP status, HTTP headers, valid SID flag, response body
        """
        self._install_plugin_actions()
        self._proc_time = time.time()
        path = path if path is not None else self._import_req_path()
        named_args = {}
        headers = []
        action_metadata = self._get_method_metadata(path[0])
        return_type = action_metadata.get('return_type', 'html')
        try:
            self.init_session()
            if self.is_action(path[0], action_metadata):
                named_args = self.pre_dispatch(named_args, action_metadata)
                self._pre_action_validate()
                methodname, tmpl, result = self.process_action(
                    path[0], named_args)
            else:
                raise NotFoundException(_('Unknown action [%s]') % path[0])
        except CorpusForbiddenException:
            methodname, tmpl, result = self._run_message_action(
                named_args, return_type)
        except UserActionException as ex:
            self._status = ex.code
            self.add_system_message('error', fetch_exception_msg(ex))
            methodname, tmpl, result = self._run_message_action(
                named_args, return_type)
        except werkzeug.exceptions.BadRequest as ex:
            self._status = ex.code
            self.add_system_message('error',
                                    '{0}: {1}'.format(ex.name, ex.description))
            methodname, tmpl, result = self._run_message_action(
                named_args, return_type)
        except Exception as ex:
            # an error outside the action itself (i.e. pre_dispatch, action validation,
            # post_dispatch etc.)
            logging.getLogger(__name__).error(u'%s\n%s' %
                                              (ex, ''.join(get_traceback())))
            if settings.is_debug_mode():
                self._status = 500
                self.add_system_message('error', fetch_exception_msg(ex))
            else:
                self.handle_dispatch_error(ex)
            methodname, tmpl, result = self._run_message_action(
                named_args, return_type)

        # Let's test whether process_method actually invoked requested method.
        # If not (e.g. there was an error and a fallback has been used) then reload action metadata
        if methodname != path[0]:
            action_metadata = self._get_method_metadata(methodname)

        self._proc_time = round(time.time() - self._proc_time, 4)
        self.post_dispatch(methodname, action_metadata, tmpl, result)
        # response rendering
        headers += self.output_headers(return_type)
        output = StringIO.StringIO()
        if self._status < 300 or self._status >= 400:
            self.output_result(methodname,
                               tmpl,
                               result,
                               action_metadata,
                               outf=output)
        ans_body = output.getvalue()
        output.close()
        return self._export_status(), headers, self._uses_valid_sid, ans_body
Esempio n. 21
0

def set_debug_mode(app):
    from werkzeug.debug import DebuggedApplication
    app = DebuggedApplication(app)
    # profiling
    if settings.debug_level() == settings.DEBUG_AND_PROFILE:
        from werkzeug.middleware.profiler import ProfilerMiddleware
        app = ProfilerMiddleware(application, sys.stdout)
        profile_log_path = settings.get('global', 'profile_log_path')
        if profile_log_path:
            app = ProfilerMiddleware(app, open(profile_log_path), 'w')
    return app


if settings.is_debug_mode():
    application = set_debug_mode(application)

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    from werkzeug.middleware.shared_data import SharedDataMiddleware
    import argparse

    DEFAULT_PORT = 5000
    DEFAULT_ADDR = '127.0.0.1'

    parser = argparse.ArgumentParser(
        description='Starts a local development server')
    parser.add_argument('--port',
                        dest='port_num',
                        action=None,
Esempio n. 22
0
 def test_debug_mode(self):
     self.assertFalse(settings.is_debug_mode())
Esempio n. 23
0
 def test_debug_mode(self):
     self.assertFalse(settings.is_debug_mode())