Exemplo n.º 1
0
    def page_content(self):
        """Get traversable content providers for the context.

        Say, we have a viewlet manager named ExtraInfo, registered for persons.
        As viewlet managers implement IContentProvider, we can do:

        <div tal:repeat="person view/persons">
          <p tal:content="person/title"></p>
          <div tal:replace="structure person/schooltool:page_content/ExtraInfo"></div>
        </div>

        """
        if self.engine is None:
            return None
        vars = self.engine.vars
        context = self.context
        request = vars.get('request', None)
        page = view = vars.get('view', None)
        while (page is not None and
               not IPageBase.providedBy(page)):
            page = getattr(page, '__parent__', None)
        if page is None:
            page = view
            while (page is not None and
                   not IBrowserPage.providedBy(page)):
                page = getattr(page, '__parent__', None)
        providers = queryMultiAdapter(
            (context, request, page),
            IContentProviders)
        if ITALESFunctionNamespace.providedBy(providers):
            providers.setEngine(self.engine)
        return providers
Exemplo n.º 2
0
    def render_error(self, error, last_known_obj):
        """Render and log an error.
        """
        if IBrowserPage.providedBy(last_known_obj):
            #of the last obj is a view, use it's context (which should be
            # an IAcquirer)
            last_known_obj = last_known_obj.context
        if not IAcquirer.providedBy(last_known_obj):
            last_known_site = getSite()
            if last_known_site is not None:
                last_known_obj = last_known_site
        context = DefaultError(error)
        if IAcquirer.providedBy(last_known_obj):
            context = context.__of__(last_known_obj)
        error_view = queryMultiAdapter(
            (context, self.request), name='error.html')
        if IBrowserPublisher.providedBy(error_view):
            error_view, error_path = error_view.browserDefault(self.request)
            if error_path:
                raise NotImplementedError(
                    u'Error browserDefault retuned an path. '
                    u'This is not implemented.')

        if error_view is not None:
            notify(interfaces.PublicationBeforeError(
                    self.request, last_known_obj))
            try:
                error_result = error_view()
                if error_result is not None:
                    self.response.setBody(error_result)

                notify(interfaces.PublicationAfterRender(
                        self.request, error_view))

            except Exception:
                log_last_error(
                    self.request, self.response, obj=last_known_obj,
                    extra=u"Error while rendering error message")
                self.response.setStatus(500)
                self.response.setBody(ERROR_WHILE_RENDERING_ERROR_TEMPLATE)
        else:
            logger.error('No action defined for last exception')
            self.response.setStatus(500)
            self.response.setBody(DEFAULT_ERROR_TEMPLATE)
Exemplo n.º 3
0
def publish(
    request,
    module_name,
    after_list,
    debug=0,
    # Optimize:
    call_object=call_object,
    missing_name=missing_name,
    dont_publish_class=dont_publish_class,
    mapply=mapply,
):

    (bobo_before, bobo_after, object, realm, debug_mode, err_hook,
     validated_hook, transactions_manager) = get_module_info(module_name)

    parents = None
    response = None

    try:
        notify(pubevents.PubStart(request))
        # TODO pass request here once BaseRequest implements IParticipation
        newInteraction()

        request.processInputs()

        request_get = request.get
        response = request.response

        # First check for "cancel" redirect:
        if request_get('SUBMIT', '').strip().lower() == 'cancel':
            cancel = request_get('CANCEL_ACTION', '')
            if cancel:
                # Relative URLs aren't part of the spec, but are accepted by
                # some browsers.
                for part, base in zip(
                        urlparse(cancel)[:3],
                        urlparse(request['BASE1'])[:3]):
                    if not part:
                        continue
                    if not part.startswith(base):
                        cancel = ''
                        break
            if cancel:
                raise Redirect(cancel)

        after_list[0] = bobo_after
        if debug_mode:
            response.debug_mode = debug_mode
        if realm and not request.get('REMOTE_USER', None):
            response.realm = realm

        noSecurityManager()
        if bobo_before is not None:
            bobo_before()

        # Get the path list.
        # According to RFC1738 a trailing space in the path is valid.
        path = request_get('PATH_INFO')

        request['PARENTS'] = parents = [object]

        if transactions_manager:
            transactions_manager.begin()

        object = request.traverse(path, validated_hook=validated_hook)

        if IBrowserPage.providedBy(object):
            request.postProcessInputs()

        notify(pubevents.PubAfterTraversal(request))

        if transactions_manager:
            recordMetaData(object, request)

        result = mapply(object,
                        request.args,
                        request,
                        call_object,
                        1,
                        missing_name,
                        dont_publish_class,
                        request,
                        bind=1)
        if result is not response:
            response.setBody(result)

        notify(pubevents.PubBeforeCommit(request))

        if transactions_manager:
            transactions_manager.commit()

        notify(pubevents.PubSuccess(request))
        endInteraction()

        return response
    except:
        # save in order to give 'PubFailure' the original exception info
        exc_info = sys.exc_info()
        # DM: provide nicer error message for FTP
        sm = None
        if response is not None:
            sm = getattr(response, "setMessage", None)

        if sm is not None:
            from asyncore import compact_traceback
            cl, val = sys.exc_info()[:2]
            sm('%s: %s %s' % (getattr(cl, '__name__', cl), val,
                              debug_mode and compact_traceback()[-1] or ''))

        # debug is just used by tests (has nothing to do with debug_mode!)
        if not debug and err_hook is not None:
            retry = False
            if parents:
                parents = parents[0]
            try:
                try:
                    return err_hook(
                        parents,
                        request,
                        sys.exc_info()[0],
                        sys.exc_info()[1],
                        sys.exc_info()[2],
                    )
                except Retry:
                    if not request.supports_retry():
                        return err_hook(
                            parents,
                            request,
                            sys.exc_info()[0],
                            sys.exc_info()[1],
                            sys.exc_info()[2],
                        )
                    retry = True
            finally:
                # Note: 'abort's can fail.
                # Nevertheless, we want end request handling.
                try:
                    try:
                        notify(
                            pubevents.PubBeforeAbort(request, exc_info, retry))
                    finally:
                        if transactions_manager:
                            transactions_manager.abort()
                finally:
                    endInteraction()
                    notify(pubevents.PubFailure(request, exc_info, retry))

            # Only reachable if Retry is raised and request supports retry.
            newrequest = request.retry()
            request.close()  # Free resources held by the request.

            # Set the default layer/skin on the newly generated request
            if ISkinnable.providedBy(newrequest):
                setDefaultSkin(newrequest)
            try:
                return publish(newrequest, module_name, after_list, debug)
            finally:
                newrequest.close()

        else:
            # Note: 'abort's can fail.
            # Nevertheless, we want end request handling.
            try:
                try:
                    notify(pubevents.PubBeforeAbort(request, exc_info, False))
                finally:
                    if transactions_manager:
                        transactions_manager.abort()
            finally:
                endInteraction()
                notify(pubevents.PubFailure(request, exc_info, False))
            raise
Exemplo n.º 4
0
def publish(
    request,
    module_name,
    after_list,
    debug=0,
    # Optimize:
    call_object=call_object,
    missing_name=missing_name,
    dont_publish_class=dont_publish_class,
    mapply=mapply,
):

    (
        bobo_before,
        bobo_after,
        object,
        realm,
        debug_mode,
        err_hook,
        validated_hook,
        transactions_manager,
    ) = get_module_info(module_name)

    parents = None
    response = None

    try:
        notify(PubStart(request))
        # TODO pass request here once BaseRequest implements IParticipation
        newInteraction()

        request.processInputs()

        request_get = request.get
        response = request.response

        # First check for "cancel" redirect:
        if request_get("SUBMIT", "").strip().lower() == "cancel":
            cancel = request_get("CANCEL_ACTION", "")
            if cancel:
                # Relative URLs aren't part of the spec, but are accepted by
                # some browsers.
                for part, base in zip(urlparse(cancel)[:3], urlparse(request["BASE1"])[:3]):
                    if not part:
                        continue
                    if not part.startswith(base):
                        cancel = ""
                        break
            if cancel:
                raise Redirect, cancel

        after_list[0] = bobo_after
        if debug_mode:
            response.debug_mode = debug_mode
        if realm and not request.get("REMOTE_USER", None):
            response.realm = realm

        if bobo_before is not None:
            bobo_before()

        # Get the path list.
        # According to RFC1738 a trailing space in the path is valid.
        path = request_get("PATH_INFO")

        request["PARENTS"] = parents = [object]

        if transactions_manager:
            transactions_manager.begin()

        object = request.traverse(path, validated_hook=validated_hook)

        if IBrowserPage.providedBy(object):
            request.postProcessInputs()

        notify(PubAfterTraversal(request))

        if transactions_manager:
            transactions_manager.recordMetaData(object, request)

        result = mapply(
            object, request.args, request, call_object, 1, missing_name, dont_publish_class, request, bind=1
        )

        if result is not response:
            response.setBody(result)

        notify(PubBeforeCommit(request))

        if transactions_manager:
            transactions_manager.commit()
        endInteraction()

        notify(PubSuccess(request))

        return response
    except:
        # save in order to give 'PubFailure' the original exception info
        exc_info = sys.exc_info()
        # DM: provide nicer error message for FTP
        sm = None
        if response is not None:
            sm = getattr(response, "setMessage", None)

        if sm is not None:
            from asyncore import compact_traceback

            cl, val = sys.exc_info()[:2]
            sm("%s: %s %s" % (getattr(cl, "__name__", cl), val, debug_mode and compact_traceback()[-1] or ""))

        # debug is just used by tests (has nothing to do with debug_mode!)
        if not debug and err_hook is not None:
            retry = False
            if parents:
                parents = parents[0]
            try:
                try:
                    return err_hook(parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
                except Retry:
                    if not request.supports_retry():
                        return err_hook(parents, request, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
                    retry = True
            finally:
                # Note: 'abort's can fail. Nevertheless, we want end request handling
                try:
                    try:
                        notify(PubBeforeAbort(request, exc_info, retry))
                    finally:
                        if transactions_manager:
                            transactions_manager.abort()
                finally:
                    endInteraction()
                    notify(PubFailure(request, exc_info, retry))

            # Only reachable if Retry is raised and request supports retry.
            newrequest = request.retry()
            request.close()  # Free resources held by the request.

            # Set the default layer/skin on the newly generated request
            if ISkinnable.providedBy(newrequest):
                setDefaultSkin(newrequest)
            try:
                return publish(newrequest, module_name, after_list, debug)
            finally:
                newrequest.close()

        else:
            # Note: 'abort's can fail. Nevertheless, we want end request handling
            try:
                try:
                    notify(PubBeforeAbort(request, exc_info, False))
                finally:
                    if transactions_manager:
                        transactions_manager.abort()
            finally:
                endInteraction()
                notify(PubFailure(request, exc_info, False))
            raise
def publish(request, module_name, after_list, debug=0,
            # Optimize:
            call_object=call_object,
            missing_name=missing_name,
            dont_publish_class=dont_publish_class,
            mapply=mapply,
            ):

    (bobo_before, bobo_after, object, realm, debug_mode, err_hook,
     validated_hook, transactions_manager)= get_module_info(module_name)

    parents=None
    response=None

    try:
        time_started = time.clock()

        notify(PubStart(request))
        # TODO pass request here once BaseRequest implements IParticipation
        newInteraction()

        request.processInputs()

        request_get=request.get
        response=request.response

        # First check for "cancel" redirect:
        if request_get('SUBMIT','').strip().lower()=='cancel':
            cancel=request_get('CANCEL_ACTION','')
            if cancel:
                raise Redirect, cancel

        after_list[0]=bobo_after
        if debug_mode:
            response.debug_mode=debug_mode
        if realm and not request.get('REMOTE_USER',None):
            response.realm=realm

        if bobo_before is not None:
            bobo_before()

        # Get the path list.
        # According to RFC1738 a trailing space in the path is valid.
        path=request_get('PATH_INFO')

        request['PARENTS']=parents=[object]

        if transactions_manager:
            transactions_manager.begin()

        object=request.traverse(path, validated_hook=validated_hook)

        if IBrowserPage.providedBy(object):
            request.postProcessInputs()

        notify(PubAfterTraversal(request))

        if transactions_manager:
            transactions_manager.recordMetaData(object, request)

        result=mapply(object, request.args, request,
                      call_object,1,
                      missing_name,
                      dont_publish_class,
                      request, bind=1)

        if result is not response:
            response.setBody(result)

        notify(PubBeforeCommit(request))

        if transactions_manager:
            transactions_manager.commit()
        endInteraction()

        notify(PubSuccess(request))

        if Globals.DevelopmentMode and not path.endswith( ( '.css', '.js', '.kss', '.png', '.gif', '.jpg' ) ):
            LOG.info('Request: ' + str(int((time.clock() - time_started)*1000)).rjust(4) + 'ms @ ' + path)

        return response
    except:
        # save in order to give 'PubFailure' the original exception info
        exc_info = sys.exc_info()
        # DM: provide nicer error message for FTP
        sm = None
        if response is not None:
            sm = getattr(response, "setMessage", None)

        if sm is not None:
            from asyncore import compact_traceback
            cl,val= sys.exc_info()[:2]
            sm('%s: %s %s' % (
                getattr(cl,'__name__',cl), val,
                debug_mode and compact_traceback()[-1] or ''))

        # debug is just used by tests (has nothing to do with debug_mode!)
        if not debug and err_hook is not None:
            retry = False
            if parents:
                parents=parents[0]
            try:
                try:
                    return err_hook(parents, request,
                                    sys.exc_info()[0],
                                    sys.exc_info()[1],
                                    sys.exc_info()[2],
                                    )
                except Retry:
                    if not request.supports_retry():
                        return err_hook(parents, request,
                                        sys.exc_info()[0],
                                        sys.exc_info()[1],
                                        sys.exc_info()[2],
                                        )
                    retry = True
            finally:
                # Note: 'abort's can fail. Nevertheless, we want end request handling
                try:
                    try:
                        notify(PubBeforeAbort(request, exc_info, retry))
                    finally:
                        if transactions_manager:
                            transactions_manager.abort()
                finally:
                    endInteraction()
                    notify(PubFailure(request, exc_info, retry))

            # Only reachable if Retry is raised and request supports retry.
            newrequest=request.retry()
            request.close()  # Free resources held by the request.

            # Set the default layer/skin on the newly generated request
            if ISkinnable.providedBy(newrequest):
                setDefaultSkin(newrequest)
            try:
                return publish(newrequest, module_name, after_list, debug)
            finally:
                newrequest.close()

        else:
            # Note: 'abort's can fail. Nevertheless, we want end request handling
            try:
                try:
                    notify(PubBeforeAbort(request, exc_info, False))
                finally:
                    if transactions_manager:
                        transactions_manager.abort()
            finally:
                endInteraction()
                notify(PubFailure(request, exc_info, False))
            raise