示例#1
0
def render(renderer_name, value, request=None, package=None):
    """ Using the renderer ``renderer_name`` (a template
    or a static renderer), render the value (or set of values) present
    in ``value``. Return the result of the renderer's ``__call__``
    method (usually a string or Unicode).

    If the ``renderer_name`` refers to a file on disk, such as when the
    renderer is a template, it's usually best to supply the name as an
    :term:`asset specification`
    (e.g. ``packagename:path/to/template.pt``).

    You may supply a relative asset spec as ``renderer_name``.  If
    the ``package`` argument is supplied, a relative renderer path
    will be converted to an absolute asset specification by
    combining the package ``package`` with the relative
    asset specification ``renderer_name``.  If ``package``
    is ``None`` (the default), the package name of the *caller* of
    this function will be used as the package.

    The ``value`` provided will be supplied as the input to the
    renderer.  Usually, for template renderings, this should be a
    dictionary.  For other renderers, this will need to be whatever
    sort of value the renderer expects.

    The 'system' values supplied to the renderer will include a basic set of
    top-level system names, such as ``request``, ``context``,
    ``renderer_name``, and ``view``.  See :ref:`renderer_system_values` for
    the full list.  If :term:`renderer globals` have been specified, these
    will also be used to augment the value.

    Supply a ``request`` parameter in order to provide the renderer
    with the most correct 'system' values (``request`` and ``context``
    in particular).

    """
    try:
        registry = request.registry
    except AttributeError:
        registry = None
    if package is None:
        package = caller_package()
    helper = RendererHelper(name=renderer_name,
                            package=package,
                            registry=registry)

    with hide_attrs(request, 'response'):
        result = helper.render(value, None, request=request)

    return result
示例#2
0
def render(renderer_name, value, request=None, package=None):
    """ Using the renderer ``renderer_name`` (a template
    or a static renderer), render the value (or set of values) present
    in ``value``. Return the result of the renderer's ``__call__``
    method (usually a string or Unicode).

    If the ``renderer_name`` refers to a file on disk, such as when the
    renderer is a template, it's usually best to supply the name as an
    :term:`asset specification`
    (e.g. ``packagename:path/to/template.pt``).

    You may supply a relative asset spec as ``renderer_name``.  If
    the ``package`` argument is supplied, a relative renderer path
    will be converted to an absolute asset specification by
    combining the package ``package`` with the relative
    asset specification ``renderer_name``.  If ``package``
    is ``None`` (the default), the package name of the *caller* of
    this function will be used as the package.

    The ``value`` provided will be supplied as the input to the
    renderer.  Usually, for template renderings, this should be a
    dictionary.  For other renderers, this will need to be whatever
    sort of value the renderer expects.

    The 'system' values supplied to the renderer will include a basic set of
    top-level system names, such as ``request``, ``context``,
    ``renderer_name``, and ``view``.  See :ref:`renderer_system_values` for
    the full list.  If :term:`renderer globals` have been specified, these
    will also be used to augment the value.

    Supply a ``request`` parameter in order to provide the renderer
    with the most correct 'system' values (``request`` and ``context``
    in particular).

    """
    try:
        registry = request.registry
    except AttributeError:
        registry = None
    if package is None:
        package = caller_package()
    helper = RendererHelper(
        name=renderer_name, package=package, registry=registry
    )

    with hide_attrs(request, 'response'):
        result = helper.render(value, None, request=request)

    return result
示例#3
0
    def invoke_exception_view(
        self,
        exc_info=None,
        request=None,
        secure=True,
        reraise=False,
    ):
        """ Executes an exception view related to the request it's called upon.
        The arguments it takes are these:

        ``exc_info``

            If provided, should be a 3-tuple in the form provided by
            ``sys.exc_info()``.  If not provided,
            ``sys.exc_info()`` will be called to obtain the current
            interpreter exception information.  Default: ``None``.

        ``request``

            If the request to be used is not the same one as the instance that
            this method is called upon, it may be passed here.  Default:
            ``None``.

        ``secure``

            If the exception view should not be rendered if the current user
            does not have the appropriate permission, this should be ``True``.
            Default: ``True``.

        ``reraise``

            A boolean indicating whether the original error should be reraised
            if a :term:`response` object could not be created. If ``False``
            then an :class:`pyramid.httpexceptions.HTTPNotFound`` exception
            will be raised. Default: ``False``.

        If a response is generated then ``request.exception`` and
        ``request.exc_info`` will be left at the values used to render the
        response. Otherwise the previous values for ``request.exception`` and
        ``request.exc_info`` will be restored.

        .. versionadded:: 1.7

        .. versionchanged:: 1.9
           The ``request.exception`` and ``request.exc_info`` properties will
           reflect the exception used to render the response where previously
           they were reset to the values prior to invoking the method.

           Also added the ``reraise`` argument.

        """
        if request is None:
            request = self
        registry = getattr(request, 'registry', None)
        if registry is None:
            registry = get_current_registry()

        if registry is None:
            raise RuntimeError("Unable to retrieve registry")

        if exc_info is None:
            exc_info = sys.exc_info()

        exc = exc_info[1]
        attrs = request.__dict__
        context_iface = providedBy(exc)

        # clear old generated request.response, if any; it may
        # have been mutated by the view, and its state is not
        # sane (e.g. caching headers)
        with hide_attrs(request, 'response', 'exc_info', 'exception'):
            attrs['exception'] = exc
            attrs['exc_info'] = exc_info
            # we use .get instead of .__getitem__ below due to
            # https://github.com/Pylons/pyramid/issues/700
            request_iface = attrs.get('request_iface', IRequest)

            manager.push({'request': request, 'registry': registry})

            try:
                response = _call_view(
                    registry,
                    request,
                    exc,
                    context_iface,
                    '',
                    view_types=None,
                    view_classifier=IExceptionViewClassifier,
                    secure=secure,
                    request_iface=request_iface.combined,
                )
            except:
                if reraise:
                    reraise_(*exc_info)
                raise
            finally:
                manager.pop()

        if response is None:
            if reraise:
                reraise_(*exc_info)
            raise HTTPNotFound

        # successful response, overwrite exception/exc_info
        attrs['exception'] = exc
        attrs['exc_info'] = exc_info
        return response
示例#4
0
    def _callFUT(self, obj, *attrs):
        from pyramid.util import hide_attrs

        return hide_attrs(obj, *attrs)
示例#5
0
 def _callFUT(self, obj, *attrs):
     from pyramid.util import hide_attrs
     return hide_attrs(obj, *attrs)
示例#6
0
    def invoke_exception_view(self, exc_info=None, request=None, secure=True):
        """ Executes an exception view related to the request it's called upon.
        The arguments it takes are these:

        ``exc_info``

            If provided, should be a 3-tuple in the form provided by
            ``sys.exc_info()``.  If not provided,
            ``sys.exc_info()`` will be called to obtain the current
            interpreter exception information.  Default: ``None``.

        ``request``

            If the request to be used is not the same one as the instance that
            this method is called upon, it may be passed here.  Default:
            ``None``.

        ``secure``

            If the exception view should not be rendered if the current user
            does not have the appropriate permission, this should be ``True``.
            Default: ``True``.

        If called with no arguments, it uses the global exception information
        returned by ``sys.exc_info()`` as ``exc_info``, the request
        object that this method is attached to as the ``request``, and
        ``True`` for ``secure``.

        This method returns a :term:`response` object or ``None`` if no
        matching exception view can be found."""

        if request is None:
            request = self
        registry = getattr(request, 'registry', None)
        if registry is None:
            registry = get_current_registry()
        if exc_info is None:
            exc_info = sys.exc_info()
        exc = exc_info[1]
        attrs = request.__dict__
        context_iface = providedBy(exc)

        # clear old generated request.response, if any; it may
        # have been mutated by the view, and its state is not
        # sane (e.g. caching headers)
        with hide_attrs(request, 'exception', 'exc_info', 'response'):
            attrs['exception'] = exc
            attrs['exc_info'] = exc_info
            # we use .get instead of .__getitem__ below due to
            # https://github.com/Pylons/pyramid/issues/700
            request_iface = attrs.get('request_iface', IRequest)
            response = _call_view(
                registry,
                request,
                exc,
                context_iface,
                '',
                view_types=None,
                view_classifier=IExceptionViewClassifier,
                secure=secure,
                request_iface=request_iface.combined,
            )
            return response
示例#7
0
def render_to_response(renderer_name,
                       value,
                       request=None,
                       package=None,
                       response=None):
    """ Using the renderer ``renderer_name`` (a template
    or a static renderer), render the value (or set of values) using
    the result of the renderer's ``__call__`` method (usually a string
    or Unicode) as the response body.

    If the renderer name refers to a file on disk (such as when the
    renderer is a template), it's usually best to supply the name as a
    :term:`asset specification`.

    You may supply a relative asset spec as ``renderer_name``.  If
    the ``package`` argument is supplied, a relative renderer name
    will be converted to an absolute asset specification by
    combining the package ``package`` with the relative
    asset specification ``renderer_name``.  If you do
    not supply a ``package`` (or ``package`` is ``None``) the package
    name of the *caller* of this function will be used as the package.

    The ``value`` provided will be supplied as the input to the
    renderer.  Usually, for template renderings, this should be a
    dictionary.  For other renderers, this will need to be whatever
    sort of value the renderer expects.

    The 'system' values supplied to the renderer will include a basic set of
    top-level system names, such as ``request``, ``context``,
    ``renderer_name``, and ``view``.  See :ref:`renderer_system_values` for
    the full list.  If :term:`renderer globals` have been specified, these
    will also be used to argument the value.

    Supply a ``request`` parameter in order to provide the renderer
    with the most correct 'system' values (``request`` and ``context``
    in particular). Keep in mind that any changes made to ``request.response``
    prior to calling this function will not be reflected in the resulting
    response object. A new response object will be created for each call
    unless one is passed as the ``response`` argument.

    .. versionchanged:: 1.6
       In previous versions, any changes made to ``request.response`` outside
       of this function call would affect the returned response. This is no
       longer the case. If you wish to send in a pre-initialized response
       then you may pass one in the ``response`` argument.

    """
    try:
        registry = request.registry
    except AttributeError:
        registry = None
    if package is None:
        package = caller_package()
    helper = RendererHelper(name=renderer_name,
                            package=package,
                            registry=registry)

    with hide_attrs(request, 'response'):
        if response is not None:
            request.response = response
        result = helper.render_to_response(value, None, request=request)

    return result
示例#8
0
    def invoke_exception_view(
        self,
        exc_info=None,
        request=None,
        secure=True
        ):
        """ Executes an exception view related to the request it's called upon.
        The arguments it takes are these:

        ``exc_info``

            If provided, should be a 3-tuple in the form provided by
            ``sys.exc_info()``.  If not provided,
            ``sys.exc_info()`` will be called to obtain the current
            interpreter exception information.  Default: ``None``.

        ``request``

            If the request to be used is not the same one as the instance that
            this method is called upon, it may be passed here.  Default:
            ``None``.

        ``secure``

            If the exception view should not be rendered if the current user
            does not have the appropriate permission, this should be ``True``.
            Default: ``True``.

        If called with no arguments, it uses the global exception information
        returned by ``sys.exc_info()`` as ``exc_info``, the request
        object that this method is attached to as the ``request``, and
        ``True`` for ``secure``.

        This method returns a :term:`response` object or raises
        :class:`pyramid.httpexceptions.HTTPNotFound` if a matching view cannot
        be found."""

        if request is None:
            request = self
        registry = getattr(request, 'registry', None)
        if registry is None:
            registry = get_current_registry()
        if exc_info is None:
            exc_info = sys.exc_info()
        exc = exc_info[1]
        attrs = request.__dict__
        context_iface = providedBy(exc)

        # clear old generated request.response, if any; it may
        # have been mutated by the view, and its state is not
        # sane (e.g. caching headers)
        with hide_attrs(request, 'exception', 'exc_info', 'response'):
            attrs['exception'] = exc
            attrs['exc_info'] = exc_info
            # we use .get instead of .__getitem__ below due to
            # https://github.com/Pylons/pyramid/issues/700
            request_iface = attrs.get('request_iface', IRequest)
            response = _call_view(
                registry,
                request,
                exc,
                context_iface,
                '',
                view_types=None,
                view_classifier=IExceptionViewClassifier,
                secure=secure,
                request_iface=request_iface.combined,
                )
            if response is None:
                raise HTTPNotFound
            return response
示例#9
0
def render_to_response(renderer_name,
                       value,
                       request=None,
                       package=None,
                       response=None):
    """ Using the renderer ``renderer_name`` (a template
    or a static renderer), render the value (or set of values) using
    the result of the renderer's ``__call__`` method (usually a string
    or Unicode) as the response body.

    If the renderer name refers to a file on disk (such as when the
    renderer is a template), it's usually best to supply the name as a
    :term:`asset specification`.

    You may supply a relative asset spec as ``renderer_name``.  If
    the ``package`` argument is supplied, a relative renderer name
    will be converted to an absolute asset specification by
    combining the package ``package`` with the relative
    asset specification ``renderer_name``.  If you do
    not supply a ``package`` (or ``package`` is ``None``) the package
    name of the *caller* of this function will be used as the package.

    The ``value`` provided will be supplied as the input to the
    renderer.  Usually, for template renderings, this should be a
    dictionary.  For other renderers, this will need to be whatever
    sort of value the renderer expects.

    The 'system' values supplied to the renderer will include a basic set of
    top-level system names, such as ``request``, ``context``,
    ``renderer_name``, and ``view``.  See :ref:`renderer_system_values` for
    the full list.  If :term:`renderer globals` have been specified, these
    will also be used to argument the value.

    Supply a ``request`` parameter in order to provide the renderer
    with the most correct 'system' values (``request`` and ``context``
    in particular). Keep in mind that any changes made to ``request.response``
    prior to calling this function will not be reflected in the resulting
    response object. A new response object will be created for each call
    unless one is passed as the ``response`` argument.

    .. versionchanged:: 1.6
       In previous versions, any changes made to ``request.response`` outside
       of this function call would affect the returned response. This is no
       longer the case. If you wish to send in a pre-initialized response
       then you may pass one in the ``response`` argument.

    """
    try:
        registry = request.registry
    except AttributeError:
        registry = None
    if package is None:
        package = caller_package()
    helper = RendererHelper(name=renderer_name, package=package,
                            registry=registry)

    with hide_attrs(request, 'response'):
        if response is not None:
            request.response = response
        result = helper.render_to_response(value, None, request=request)

    return result
示例#10
0
文件: view.py 项目: Pylons/pyramid
    def invoke_exception_view(
        self, exc_info=None, request=None, secure=True, reraise=False
    ):
        """ Executes an exception view related to the request it's called upon.
        The arguments it takes are these:

        ``exc_info``

            If provided, should be a 3-tuple in the form provided by
            ``sys.exc_info()``.  If not provided,
            ``sys.exc_info()`` will be called to obtain the current
            interpreter exception information.  Default: ``None``.

        ``request``

            If the request to be used is not the same one as the instance that
            this method is called upon, it may be passed here.  Default:
            ``None``.

        ``secure``

            If the exception view should not be rendered if the current user
            does not have the appropriate permission, this should be ``True``.
            Default: ``True``.

        ``reraise``

            A boolean indicating whether the original error should be reraised
            if a :term:`response` object could not be created. If ``False``
            then an :class:`pyramid.httpexceptions.HTTPNotFound`` exception
            will be raised. Default: ``False``.

        If a response is generated then ``request.exception`` and
        ``request.exc_info`` will be left at the values used to render the
        response. Otherwise the previous values for ``request.exception`` and
        ``request.exc_info`` will be restored.

        .. versionadded:: 1.7

        .. versionchanged:: 1.9
           The ``request.exception`` and ``request.exc_info`` properties will
           reflect the exception used to render the response where previously
           they were reset to the values prior to invoking the method.

           Also added the ``reraise`` argument.

        """
        if request is None:
            request = self
        registry = getattr(request, 'registry', None)
        if registry is None:
            registry = get_current_registry()

        if registry is None:
            raise RuntimeError("Unable to retrieve registry")

        if exc_info is None:
            exc_info = sys.exc_info()

        exc = exc_info[1]
        attrs = request.__dict__
        context_iface = providedBy(exc)

        # clear old generated request.response, if any; it may
        # have been mutated by the view, and its state is not
        # sane (e.g. caching headers)
        with hide_attrs(request, 'response', 'exc_info', 'exception'):
            attrs['exception'] = exc
            attrs['exc_info'] = exc_info
            # we use .get instead of .__getitem__ below due to
            # https://github.com/Pylons/pyramid/issues/700
            request_iface = attrs.get('request_iface', IRequest)

            manager.push({'request': request, 'registry': registry})

            try:
                response = _call_view(
                    registry,
                    request,
                    exc,
                    context_iface,
                    '',
                    view_types=None,
                    view_classifier=IExceptionViewClassifier,
                    secure=secure,
                    request_iface=request_iface.combined,
                )
            except Exception:
                if reraise:
                    reraise_(*exc_info)
                raise
            finally:
                manager.pop()

        if response is None:
            if reraise:
                reraise_(*exc_info)
            raise HTTPNotFound

        # successful response, overwrite exception/exc_info
        attrs['exception'] = exc
        attrs['exc_info'] = exc_info
        return response