当前位置: 首页>>代码示例>>Python>>正文


Python ResponseUtil.make_empty方法代码示例

本文整理汇总了Python中indico.web.flask.util.ResponseUtil.make_empty方法的典型用法代码示例。如果您正苦于以下问题:Python ResponseUtil.make_empty方法的具体用法?Python ResponseUtil.make_empty怎么用?Python ResponseUtil.make_empty使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在indico.web.flask.util.ResponseUtil的用法示例。


在下文中一共展示了ResponseUtil.make_empty方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: RH

# 需要导入模块: from indico.web.flask.util import ResponseUtil [as 别名]
# 或者: from indico.web.flask.util.ResponseUtil import make_empty [as 别名]

#.........这里部分代码省略.........
        ContextManager.destroy()
        ContextManager.set('currentRH', self)
        g.rh = self

        #redirect to https if necessary
        if self._checkHttpsRedirect():
            return self._responseUtil.make_redirect()

        DBMgr.getInstance().startRequest()
        textLog.append("%s : Database request started" % (datetime.now() - self._startTime))
        Logger.get('requestHandler').info('[pid=%s] Request %s started' % (
            os.getpid(), request))

        try:
            for i, retry in enumerate(transaction.attempts(max_retries)):
                with retry:
                    if i > 0:
                        signals.before_retry.send()

                    try:
                        Logger.get('requestHandler').info('\t[pid=%s] from host %s' % (os.getpid(), request.remote_addr))
                        profile_name, res = self._process_retry(params, i, profile, forced_conflicts)
                        signals.after_process.send()
                        if i < forced_conflicts:  # raise conflict error if enabled to easily handle conflict error case
                            raise ConflictError
                        transaction.commit()
                        DBMgr.getInstance().endRequest(commit=False)
                        break
                    except (ConflictError, POSKeyError):
                        transaction.abort()
                        import traceback
                        # only log conflict if it wasn't forced
                        if i >= forced_conflicts:
                            Logger.get('requestHandler').warning('Conflict in Database! (Request %s)\n%s' % (request, traceback.format_exc()))
                    except ClientDisconnected:
                        transaction.abort()
                        Logger.get('requestHandler').warning('Client Disconnected! (Request {})'.format(request))
                        time.sleep(i)
            self._process_success()
        except Exception as e:
            transaction.abort()
            res = self._getMethodByExceptionName(e)(e)

        totalTime = (datetime.now() - self._startTime)
        textLog.append('{} : Request ended'.format(totalTime))

        # log request timing
        if profile and totalTime > timedelta(0, 1) and os.path.isfile(profile_name):
            rep = Config.getInstance().getTempDir()
            stats = pstats.Stats(profile_name)
            stats.strip_dirs()
            stats.sort_stats('cumulative', 'time', 'calls')
            stats.dump_stats(os.path.join(rep, 'IndicoRequestProfile.log'))
            output = StringIO.StringIO()
            sys.stdout = output
            stats.print_stats(100)
            sys.stdout = sys.__stdout__
            s = output.getvalue()
            f = file(os.path.join(rep, 'IndicoRequest.log'), 'a+')
            f.write('--------------------------------\n')
            f.write('URL     : {}\n'.format(request.url))
            f.write('{} : start request\n'.format(self._startTime))
            f.write('params:{}'.format(params))
            f.write('\n'.join(textLog))
            f.write('\n')
            f.write('retried : {}\n'.format(10-retry))
            f.write(s)
            f.write('--------------------------------\n\n')
            f.close()
        if profile and profile_name and os.path.exists(profile_name):
            os.remove(profile_name)

        if self._responseUtil.call:
            return self._responseUtil.make_call()

        # In case of no process needed, we should return empty string to avoid erroneous output
        # specially with getVars breaking the JS files.
        if not self._doProcess or res is None:
            return self._responseUtil.make_empty()

        return self._responseUtil.make_response(res)

    def _getMethodByExceptionName(self, e):
        exception_name = {
            'NotFound': 'NotFoundError',
            'MaKaCError': 'GeneralError',
            'IndicoError': 'GeneralError',
            'ValueError': 'UnexpectedError',
            'Exception': 'UnexpectedError',
            'AccessControlError': 'AccessError'
        }.get(type(e).__name__, type(e).__name__)
        return getattr(self, '_process{}'.format(exception_name), self._processUnexpectedError)

    def _deleteTempFiles(self):
        if len(self._tempFilesToDelete) > 0:
            for f in self._tempFilesToDelete:
                if f is not None:
                    os.remove(f)

    relativeURL = None
开发者ID:NIIF,项目名称:indico,代码行数:104,代码来源:base.py

示例2: RH

# 需要导入模块: from indico.web.flask.util import ResponseUtil [as 别名]
# 或者: from indico.web.flask.util.ResponseUtil import make_empty [as 别名]

#.........这里部分代码省略.........
        This method is called after _process_args and is a good place
        to check if the user is permitted to perform some actions.
        """

    def _process(self):
        """Dispatch to a method named ``_process_<verb>``.

        Except for RESTful endpoints it is usually best to just
        override this method, especially when using WTForms.
        """
        method = getattr(self, '_process_' + request.method, None)
        if method is None:
            valid_methods = [m for m in HTTP_VERBS if hasattr(self, '_process_' + m)]
            raise MethodNotAllowed(valid_methods)
        return method()

    def _check_csrf(self):
        token = request.headers.get('X-CSRF-Token') or request.form.get('csrf_token')
        if token is None:
            # Might be a WTForm with a prefix. In that case the field name is '<prefix>-csrf_token'
            token = next((v for k, v in request.form.iteritems() if k.endswith('-csrf_token')), None)
        if self.CSRF_ENABLED and request.method != 'GET' and token != session.csrf_token:
            msg = _("It looks like there was a problem with your current session. Please use your browser's back "
                    "button, reload the page and try again.")
            raise BadRequest(msg)

    def _check_event_feature(self):
        from indico.modules.events.features.util import require_feature
        event_id = request.view_args.get('confId') or request.view_args.get('event_id')
        if event_id is not None:
            require_feature(event_id, self.EVENT_FEATURE)

    def _do_process(self):
        try:
            args_result = self._process_args()
            if isinstance(args_result, (current_app.response_class, Response)):
                return args_result
        except NoResultFound:  # sqlalchemy .one() not finding anything
            raise NotFound(_('The specified item could not be found.'))

        rv = self.normalize_url()
        if rv is not None:
            return rv

        self._check_access()
        if self.CHECK_HTML:
            Sanitization.sanitizationCheck(create_flat_args(), self.NOT_SANITIZED_FIELDS)

        if config.PROFILE:
            result = [None]
            profile_path = os.path.join(config.TEMP_DIR, '{}-{}.prof'.format(type(self).__name__, time.time()))
            cProfile.runctx('result[0] = self._process()', globals(), locals(), profile_path)
            return result[0]
        else:
            return self._process()

    def process(self):
        if request.method not in HTTP_VERBS:
            # Just to be sure that we don't get some crappy http verb we don't expect
            raise BadRequest

        res = ''
        g.rh = self
        sentry_set_tags({'rh': self.__class__.__name__})

        if self.EVENT_FEATURE is not None:
            self._check_event_feature()

        logger.info('%s %s [IP=%s] [PID=%s] [UID=%r]',
                    request.method, request.relative_url, request.remote_addr, os.getpid(), session.get('_user_id'))

        try:
            fossilize.clearCache()
            GenericMailer.flushQueue(False)
            self._check_csrf()
            res = self._do_process()
            signals.after_process.send()

            if self.commit:
                if GenericMailer.has_queue():
                    # ensure we fail early (before sending out e-mails)
                    # in case there are DB constraint violations, etc...
                    db.enforce_constraints()
                    GenericMailer.flushQueue(True)

                db.session.commit()
            else:
                db.session.rollback()
        except DatabaseError:
            db.session.rollback()
            handle_sqlalchemy_database_error()  # this will re-raise an exception
        logger.debug('Request successful')

        if res is None:
            return self._responseUtil.make_empty()

        response = self._responseUtil.make_response(res)
        if self.DENY_FRAMES:
            response.headers['X-Frame-Options'] = 'DENY'
        return response
开发者ID:DirkHoffmann,项目名称:indico,代码行数:104,代码来源:rh.py


注:本文中的indico.web.flask.util.ResponseUtil.make_empty方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。