Пример #1
0
    def get(self, path):
        if path == '/logout':
            if users.get_current_user():
                self.redirect(users.create_logout_url('/'))
            else:
                self.redirect(self.request.relative_url('/'))
            return
        setRequest(self.request)
        app = createObject('Application', self.request, self.response)
        setSite(app)
        traverser = ITraverser(app)
        stack = path.split('/')
        if stack[-1] == '':
            stack = stack[:-1]
        if stack[0] == '':
            stack = stack[1:]
        obj = traverser.traverse(self.request, self.response, stack)

        requires = getattr(obj, 'permission_required', None)
        if requires:
            user = users.get_current_user()
            if not checkPermission(obj, user, requires):
                self.redirect(users.create_login_url(self.request.uri))
                return

        if getattr(obj, 'render', None):
            self.response.out.write(obj.render())
        else:
            self.response.headers['Content-Type'] = 'text/plain'
            self.response.out.write(obj)
        getUtility(ISession).commit()
        clearRequest()
    def __call__(self):
        celery = getCelery()
        if celery.conf.task_always_eager:
            self.eager = True
            # dive out of setup, this is not run in a celery task runner
            self.app = getApp()
            return self._run()

        self.app = makerequest(getApp())
        self.app.REQUEST['PARENTS'] = [self.app]
        setRequest(self.app.REQUEST)

        transaction.begin()
        try:
            try:
                result = self._run()
                # commit transaction
                transaction.commit()
                return result
            except ConflictError as e:
                # On ZODB conflicts, retry using celery's mechanism
                transaction.abort()
                raise Retry(exc=e)
            except Exception:
                logger.warn('Error running task: %s' % traceback.format_exc())
                transaction.abort()
                raise
        finally:
            noSecurityManager()
            setSite(None)
            self.app._p_jar.close()
            clearRequest()
Пример #3
0
        def testGetURL_catalog_as_utility(self):
            request = DummyRequest()
            b = self._makeBrain(0)

            setRequest(request)
            self.assertEqual(b.getURL(), 'http://superbad.com/conflicter')
            clearRequest()
Пример #4
0
        def testGetURL_catalog_as_utility(self):
            request = DummyRequest()
            b = self._makeBrain(0)

            setRequest(request)
            self.assertEqual(b.getURL(), 'http://superbad.com/conflicter')
            clearRequest()
Пример #5
0
def publish_module(
        environ,
        start_response,
        _publish=publish,  # only for testing
        _response=None,
        _response_factory=WSGIResponse,
        _request=None,
        _request_factory=WSGIRequest,
        _module_name='Zope2'):
    module_info = get_module_info(_module_name)
    result = ()

    with closing(BytesIO()) as stdout, closing(BytesIO()) as stderr:
        response = (_response if _response is not None else _response_factory(
            stdout=stdout, stderr=stderr))
        response._http_version = environ['SERVER_PROTOCOL'].split('/')[1]
        response._server_version = environ.get('SERVER_SOFTWARE')

        request = (_request if _request is not None else _request_factory(
            environ['wsgi.input'], environ, response))

        for i in range(getattr(request, 'retry_max_count', 3) + 1):
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response):
                        response = _publish(request, new_mod_info)
                break
            except (ConflictError, TransientError) as exc:
                if request.supports_retry():
                    new_request = request.retry()
                    request.close()
                    request = new_request
                    response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if (isinstance(response.body, _FILE_TYPES)
                or IUnboundStreamIterator.providedBy(response.body)):
            result = response.body
        else:
            # If somebody used response.write, that data will be in the
            # stdout BytesIO, so we put that before the body.
            result = (stdout.getvalue(), response.body)

        for func in response.after_list:
            func()

    # Return the result body iterable.
    return result
Пример #6
0
        def testGetObjectHappy_catalog_as_utility(self):
            request = DummyRequest()
            b = self._makeBrain(1)

            setRequest(request)
            self.assertEqual(b.getPath(), '/happy')
            self.assertEqual(b.getObject().REQUEST, request)
            self.assertTrue(aq_base(b.getObject()) is
                            aq_base(self.cat.getobject(1)))
            clearRequest()
Пример #7
0
        def testGetObjectHappy_catalog_as_utility(self):
            request = DummyRequest()
            b = self._makeBrain(1)

            setRequest(request)
            self.assertEqual(b.getPath(), '/happy')
            self.assertEqual(b.getObject().REQUEST, request)
            self.assertTrue(
                aq_base(b.getObject()) is aq_base(self.cat.getobject(1)))
            clearRequest()
Пример #8
0
    def test_searchResults_brain(self):
        site = DummySite('site')
        site._setObject('dummy', self._makeContent(catalog=1))
        ctool = self._makeOne().__of__(site)
        ctool.addIndex('meta_type', 'FieldIndex')
        ctool.catalog_object(site.dummy, '/dummy')

        query = {'meta_type': 'Dummy'}
        brain = ctool.searchResults(query)[0]

        setRequest(self.REQUEST)
        self.assertEqual('/dummy', brain.getPath())
        self.assertEqual('http://nohost/dummy', brain.getURL())
        self.assertEqual(site.dummy, brain.getObject())
        self.assertTrue(hasattr(brain.getObject(), 'REQUEST'))
        clearRequest()
Пример #9
0
    def test_searchResults_brain(self):
        site = DummySite('site')
        site._setObject('dummy', self._makeContent(catalog=1))
        ctool = self._makeOne().__of__(site)
        ctool.addIndex('meta_type', 'FieldIndex')
        ctool.catalog_object(site.dummy, '/dummy')

        query = {'meta_type': 'Dummy'}
        brain = ctool.searchResults(query)[0]

        setRequest(self.REQUEST)
        self.assertEqual('/dummy', brain.getPath())
        self.assertEqual('http://nohost/dummy', brain.getURL())
        self.assertEqual(site.dummy, brain.getObject())
        self.assertTrue(hasattr(brain.getObject(), 'REQUEST'))
        clearRequest()
Пример #10
0
    def test_HomeFolder_methods(self):
        from Products.CMFCore.interfaces import IMembershipTool

        mtool = getSiteManager().getUtility(IMembershipTool)
        setRequest(self.REQUEST)
        self.assertEqual(mtool.getHomeFolder(id='member_foo'), None)
        self.assertEqual(mtool.getHomeUrl(id='member_foo'), None)
        self.site._setObject('Members', PortalFolder('Members'))
        self.assertEqual(mtool.getHomeFolder(id='member_foo'), None)
        self.assertEqual(mtool.getHomeUrl(id='member_foo'), None)
        self.site.Members._setObject('member_foo', PortalFolder('member_foo'))
        self.assertEqual(mtool.getHomeFolder(id='member_foo'),
                         self.site.Members.member_foo)
        self.assertEqual(mtool.getHomeUrl(id='member_foo'),
                         'http://nohost/bar/site/Members/member_foo')
        clearRequest()
    def test_HomeFolder_methods(self):
        from Products.CMFCore.interfaces import IMembershipTool

        mtool = getSiteManager().getUtility(IMembershipTool)
        setRequest(self.REQUEST)
        self.assertEqual(mtool.getHomeFolder(id='member_foo'), None)
        self.assertEqual(mtool.getHomeUrl(id='member_foo'), None)
        self.site._setObject('Members', PortalFolder('Members'))
        self.assertEqual(mtool.getHomeFolder(id='member_foo'), None)
        self.assertEqual(mtool.getHomeUrl(id='member_foo'), None)
        self.site.Members._setObject('member_foo', PortalFolder('member_foo'))
        self.assertEqual(mtool.getHomeFolder(id='member_foo'),
                         self.site.Members.member_foo)
        self.assertEqual(mtool.getHomeUrl(id='member_foo'),
                         'http://nohost/bar/site/Members/member_foo')
        clearRequest()
Пример #12
0
    def setUpPloneSite(self, portal):
        # Configure five.globalrequest
        portal.REQUEST['PARENTS'] = [portal.__parent__]
        setRequest(portal.REQUEST)

        # Install into Plone site using portal_setup
        applyProfile(portal, 'plone.app.contenttypes:default')
        applyProfile(portal, 'plone.app.mosaic:default')
        applyProfile(portal, 'castle.cms:default')
        portal.portal_workflow.setDefaultChain('simple_publication_workflow')

        install.tiles(portal, portal.REQUEST)
        combine_bundles(portal)

        # Clear globalrequest
        clearRequest()
Пример #13
0
    def setUpPloneSite(self, portal):
        # Configure five.globalrequest
        portal.REQUEST['PARENTS'] = [portal.__parent__]
        setRequest(portal.REQUEST)

        # Set the default workflow
        portal.portal_workflow.setDefaultChain("simple_publication_workflow")

        # Install into Plone site using portal_setup
        applyProfile(portal, 'plone.app.mosaic:default')
        applyProfile(portal, 'plone.app.mosaic:bbb')

        ## This was a bad idea, because we want to run CMFPlone tests
        # enable_layout_view(portal)

        # Clear globalrequest
        clearRequest()
Пример #14
0
    def setUpPloneSite(self, portal):
        # Configure five.globalrequest
        portal.REQUEST['PARENTS'] = [portal.__parent__]
        setRequest(portal.REQUEST)

        # Set the default workflow
        portal.portal_workflow.setDefaultChain("simple_publication_workflow")

        # Install into Plone site using portal_setup
        applyProfile(portal, 'plone.app.mosaic:default')
        applyProfile(portal, 'plone.app.mosaic:bbb')

        ## This was a bad idea, because we want to run CMFPlone tests
        # enable_layout_view(portal)

        # Clear globalrequest
        clearRequest()
Пример #15
0
    def setUpPloneSite(self, portal):
        # Configure five.globalrequest
        portal.REQUEST['PARENTS'] = [portal.__parent__]
        setRequest(portal.REQUEST)

        # Set the default workflow
        portal.portal_workflow.setDefaultChain("simple_publication_workflow")

        # Install into Plone site using portal_setup
        applyProfile(portal, 'plone.app.contenttypes:default')
        if not HAVE_PLONE_5:
            applyProfile(portal, 'plone.app.widgets:default')
        applyProfile(portal, 'plone.app.mosaic:default')
        if not HAVE_PLONE_5:
            applyProfile(portal, 'plone.app.mosaic:bbb')

        # Clear globalrequest
        clearRequest()
Пример #16
0
    def setUpPloneSite(self, portal):
        # Configure five.globalrequest
        portal.REQUEST['PARENTS'] = [portal.__parent__]
        setRequest(portal.REQUEST)

        # Set the default workflow
        portal.portal_workflow.setDefaultChain("simple_publication_workflow")

        # Install into Plone site using portal_setup
        applyProfile(portal, 'plone.app.contenttypes:default')
        if not HAVE_PLONE_5:
            applyProfile(portal, 'plone.app.widgets:default')
        applyProfile(portal, 'plone.app.mosaic:default')
        if not HAVE_PLONE_5:
            applyProfile(portal, 'plone.app.mosaic:bbb')

        # Clear globalrequest
        clearRequest()
Пример #17
0
 def tearDown(self):
     clearRequest()
     PlacelessSetup.tearDown(self)
Пример #18
0
 def publish(request, *args, **kwargs):
     try:
         setRequest(request)
         return zope_publish(request, *args, **kwargs)
     finally:
         clearRequest()
Пример #19
0
def publish_module(environ, start_response,
                   _publish=publish,  # only for testing
                   _response=None,
                   _response_factory=WSGIResponse,
                   _request=None,
                   _request_factory=WSGIRequest,
                   _module_name='Zope2'):
    module_info = get_module_info(_module_name)
    result = ()

    path_info = environ.get('PATH_INFO')
    if path_info and PY3:
        # BIG Comment, see discussion at
        # https://github.com/zopefoundation/Zope/issues/575
        #
        # The WSGI server automatically treats headers, including the
        # PATH_INFO, as latin-1 encoded bytestrings, according to PEP-3333. As
        # this causes headache I try to show the steps a URI takes in WebOb,
        # which is similar in other wsgi server implementations.
        # UTF-8 URL-encoded object-id 'täst':
        #   http://localhost/t%C3%A4st
        # unquote('/t%C3%A4st'.decode('ascii')) results in utf-8 encoded bytes
        #   b'/t\xc3\xa4st'
        # b'/t\xc3\xa4st'.decode('latin-1') latin-1 decoding due to PEP-3333
        #   '/täst'
        # We now have a latin-1 decoded text, which was actually utf-8 encoded.
        # To reverse this we have to encode with latin-1 first.
        path_info = path_info.encode('latin-1')

        # So we can now decode with the right (utf-8) encoding to get text.
        # This encode/decode two-step with different encodings works because
        # of the way PEP-3333 restricts the type of string allowable for
        # request and response metadata. The allowed characters match up in
        # both latin-1 and utf-8.
        path_info = path_info.decode('utf-8')

        environ['PATH_INFO'] = path_info
    with closing(BytesIO()) as stdout, closing(BytesIO()) as stderr:
        new_response = (
            _response
            if _response is not None
            else _response_factory(stdout=stdout, stderr=stderr))
        new_response._http_version = environ['SERVER_PROTOCOL'].split('/')[1]
        new_response._server_version = environ.get('SERVER_SOFTWARE')

        new_request = (
            _request
            if _request is not None
            else _request_factory(environ['wsgi.input'],
                                  environ,
                                  new_response))

        for i in range(getattr(new_request, 'retry_max_count', 3) + 1):
            request = new_request
            response = new_response
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response):
                        response = _publish(request, new_mod_info)
                break
            except TransientError:
                if request.supports_retry():
                    new_request = request.retry()
                    new_response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if isinstance(response.body, _FILE_TYPES) or \
           IUnboundStreamIterator.providedBy(response.body):
            result = response.body
        else:
            # If somebody used response.write, that data will be in the
            # response.stdout BytesIO, so we put that before the body.
            result = (response.stdout.getvalue(), response.body)

        for func in response.after_list:
            func()

    # Return the result body iterable.
    return result
Пример #20
0
def publish_module(environ, start_response,
                   _publish=publish,  # only for testing
                   _response=None,
                   _response_factory=WSGIResponse,
                   _request=None,
                   _request_factory=WSGIRequest,
                   _module_name='Zope2'):
    module_info = get_module_info(_module_name)
    result = ()

    path_info = environ.get('PATH_INFO')
    if path_info:
        # The WSGI server automatically treats the PATH_INFO as latin-1 encoded
        # bytestrings. Typically this is a false assumption as the browser
        # delivers utf-8 encoded PATH_INFO. We, therefore, need to encode it
        # again with latin-1 to get a utf-8 encoded bytestring. This is
        # sufficient for Python 2.
        path_info = path_info.encode('latin-1')
        if PY3:
            # In Python 3 we need unicode here, so we decode the bytestring.
            path_info = path_info.decode('utf-8')

        environ['PATH_INFO'] = path_info
    with closing(BytesIO()) as stdout, closing(BytesIO()) as stderr:
        response = (_response if _response is not None else
                    _response_factory(stdout=stdout, stderr=stderr))
        response._http_version = environ['SERVER_PROTOCOL'].split('/')[1]
        response._server_version = environ.get('SERVER_SOFTWARE')

        request = (_request if _request is not None else
                   _request_factory(environ['wsgi.input'], environ, response))

        for i in range(getattr(request, 'retry_max_count', 3) + 1):
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response):
                        response = _publish(request, new_mod_info)
                break
            except (ConflictError, TransientError) as exc:
                if request.supports_retry():
                    new_request = request.retry()
                    request.close()
                    request = new_request
                    response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if (isinstance(response.body, _FILE_TYPES) or
                IUnboundStreamIterator.providedBy(response.body)):
            result = response.body
        else:
            # If somebody used response.write, that data will be in the
            # response.stdout BytesIO, so we put that before the body.
            result = (response.stdout.getvalue(), response.body)

        for func in response.after_list:
            func()

    # Return the result body iterable.
    return result
Пример #21
0
def publish_module_standard(
        module_name,
        stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
        environ=os.environ, debug=0, request=None, response=None):
    must_die = 0
    status = 200
    after_list = [None]
    try:
        try:
            if response is None:
                response = Response(stdout=stdout, stderr=stderr)
            else:
                stdout = response.stdout

            # debug is just used by tests (has nothing to do with debug_mode!)
            response.handle_errors = not debug

            if request is None:
                request = Request(stdin, environ, response)

            setRequest(request)

            # make sure that the request we hand over has the
            # default layer/skin set on it; subsequent code that
            # wants to look up views will likely depend on it
            if ISkinnable.providedBy(request):
                setDefaultSkin(request)

            response = publish(request, module_name, after_list, debug=debug)
        except (SystemExit, ImportError):
            # XXX: Rendered ImportErrors were never caught here because they
            # were re-raised as string exceptions. Maybe we should handle
            # ImportErrors like all other exceptions. Currently they are not
            # re-raised at all, so they don't show up here.
            must_die = sys.exc_info()
            request.response.exception(1)
        except:
            # debug is just used by tests (has nothing to do with debug_mode!)
            if debug:
                raise
            request.response.exception()
            status = response.getStatus()

        if response:
            outputBody = getattr(response, 'outputBody', None)
            if outputBody is not None:
                outputBody()
            else:
                response = str(response)
                if response:
                    stdout.write(response)

        # The module defined a post-access function, call it
        if after_list[0] is not None:
            after_list[0]()

    finally:
        if request is not None:
            request.close()
            clearRequest()

    if must_die:
        # Try to turn exception value into an exit code.
        try:
            if hasattr(must_die[1], 'code'):
                code = must_die[1].code
            else:
                code = int(must_die[1])
        except:
            code = must_die[1] and 1 or 0
        if hasattr(request.response, '_requestShutdown'):
            request.response._requestShutdown(code)

        try:
            reraise(must_die[0], must_die[1], must_die[2])
        finally:
            must_die = None

    return status
Пример #22
0
 def tearDown(self):
     clearRequest()
     zope.component.testing.tearDown()
Пример #23
0
                result = self.func(*args, **kw)
                # commit transaction
                transaction.commit()
            except ConflictError, e:
                # On ZODB conflicts, retry using celery's mechanism
                transaction.abort()
                raise Retry(exc=e)
            except:
                logger.warn('Error running task: %s' % traceback.format_exc())
                transaction.abort()
                raise
        finally:
            noSecurityManager()
            setSite(None)
            self.app._p_jar.close()
            clearRequest()

        return result


class AuthorizedFunctionRunner(FunctionRunner):

    def authorize(self):
        notify(BeforeTraverseEvent(self.site, self.site.REQUEST))
        setSite(self.site)

        # set up user
        # TODO: using plone.api.get_user().getUser()
        # somehow makes the test fail, probably because the whole setRoles
        # and login() don't do everything.
        user = api.user.get(userid=self.userid).getUser()
Пример #24
0
def clear(event):
    clearRequest()
Пример #25
0
def clear(event):
    """ clear the stored request object """
    clearRequest()
Пример #26
0
 def tearDown(self):
     clearRequest()
     PlacelessSetup.tearDown(self)
Пример #27
0
def publish_module(
        environ,
        start_response,
        _publish=publish,  # only for testing
        _response=None,
        _response_factory=WSGIResponse,
        _request=None,
        _request_factory=WSGIRequest,
        _module_name='Zope2'):
    module_info = get_module_info(_module_name)
    result = ()

    path_info = environ.get('PATH_INFO')
    if path_info:
        # BIG Comment, see discussion at
        # https://github.com/zopefoundation/Zope/issues/575
        #
        # The WSGI server automatically treats headers, including the
        # PATH_INFO, as latin-1 encoded bytestrings, according to PEP-3333. As
        # this causes headache I try to show the steps a URI takes in WebOb,
        # which is similar in other wsgi server implementations.
        # UTF-8 URL-encoded object-id 'täst':
        #   http://localhost/t%C3%A4st
        # unquote('/t%C3%A4st'.decode('ascii')) results in utf-8 encoded bytes
        #   b'/t\xc3\xa4st'
        # b'/t\xc3\xa4st'.decode('latin-1') latin-1 decoding due to PEP-3333
        #   '/täst'
        # We now have a latin-1 decoded text, which was actually utf-8 encoded.
        # To reverse this we have to encode with latin-1 first.
        path_info = path_info.encode('latin-1')

        # So we can now decode with the right (utf-8) encoding to get text.
        # This encode/decode two-step with different encodings works because
        # of the way PEP-3333 restricts the type of string allowable for
        # request and response metadata. The allowed characters match up in
        # both latin-1 and utf-8.
        path_info = path_info.decode('utf-8')

        environ['PATH_INFO'] = path_info

    # See if this should be be marked up as WebDAV request.
    try:
        server_port = int(environ['SERVER_PORT'])
    except (KeyError, ValueError):
        server_port = 0

    if _WEBDAV_SOURCE_PORT and _WEBDAV_SOURCE_PORT == server_port:
        environ['WEBDAV_SOURCE_PORT'] = 1

        # GET needs special treatment. Traversal is forced to the
        # manage_DAVget method to get the unrendered sources.
        if environ['REQUEST_METHOD'].upper() == 'GET':
            environ['PATH_INFO'] = '%s/manage_DAVget' % environ['PATH_INFO']

    with closing(BytesIO()) as stdout, closing(BytesIO()) as stderr:
        new_response = (_response if _response is not None else
                        _response_factory(stdout=stdout, stderr=stderr))
        new_response._http_version = environ['SERVER_PROTOCOL'].split('/')[1]
        new_response._server_version = environ.get('SERVER_SOFTWARE')

        new_request = (_request if _request is not None else _request_factory(
            environ['wsgi.input'], environ, new_response))

        for i in range(getattr(new_request, 'retry_max_count', 3) + 1):
            request = new_request
            response = new_response
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response):
                        response = _publish(request, new_mod_info)

                        user = getSecurityManager().getUser()
                        if user is not None and \
                           user.getUserName() != 'Anonymous User':
                            environ['REMOTE_USER'] = user.getUserName()
                break
            except TransientError:
                if request.supports_retry():
                    request.delay_retry()  # Insert a time delay
                    new_request = request.retry()
                    new_response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if isinstance(response.body, _FILE_TYPES) or \
           IUnboundStreamIterator.providedBy(response.body):
            if hasattr(response.body, 'read') and \
               'wsgi.file_wrapper' in environ:
                result = environ['wsgi.file_wrapper'](response.body)
            else:
                result = response.body
        else:
            # If somebody used response.write, that data will be in the
            # response.stdout BytesIO, so we put that before the body.
            result = (response.stdout.getvalue(), response.body)

        for func in response.after_list:
            func()

    # Return the result body iterable.
    return result
Пример #28
0
 def tearDown(self):
     clearRequest()
Пример #29
0
def publish_module(
        environ,
        start_response,
        _publish=publish,  # only for testing
        _response=None,
        _response_factory=WSGIResponse,
        _request=None,
        _request_factory=WSGIRequest,
        _module_name='Zope2'):
    module_info = get_module_info(_module_name)
    result = ()

    path_info = environ.get('PATH_INFO')
    if path_info and PY3:
        # BIG Comment, see discussion at
        # https://github.com/zopefoundation/Zope/issues/575
        #
        # The WSGI server automatically treats headers, including the
        # PATH_INFO, as latin-1 encoded bytestrings, according to PEP-3333. As
        # this causes headache I try to show the steps a URI takes in WebOb,
        # which is similar in other wsgi server implementations.
        # UTF-8 URL-encoded object-id 'täst':
        #   http://localhost/t%C3%A4st
        # unquote('/t%C3%A4st'.decode('ascii')) results in utf-8 encoded bytes
        #   b'/t\xc3\xa4st'
        # b'/t\xc3\xa4st'.decode('latin-1') latin-1 decoding due to PEP-3333
        #   '/täst'
        # We now have a latin-1 decoded text, which was actually utf-8 encoded.
        # To reverse this we have to encode with latin-1 first.
        path_info = path_info.encode('latin-1')

        # So we can now decode with the right (utf-8) encoding to get text.
        # This encode/decode two-step with different encodings works because
        # of the way PEP-3333 restricts the type of string allowable for
        # request and response metadata. The allowed characters match up in
        # both latin-1 and utf-8.
        path_info = path_info.decode('utf-8')

        environ['PATH_INFO'] = path_info
    with closing(BytesIO()) as stdout, closing(BytesIO()) as stderr:
        new_response = (_response if _response is not None else
                        _response_factory(stdout=stdout, stderr=stderr))
        new_response._http_version = environ['SERVER_PROTOCOL'].split('/')[1]
        new_response._server_version = environ.get('SERVER_SOFTWARE')

        new_request = (_request if _request is not None else _request_factory(
            environ['wsgi.input'], environ, new_response))

        for i in range(getattr(new_request, 'retry_max_count', 3) + 1):
            request = new_request
            response = new_response
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response):
                        response = _publish(request, new_mod_info)
                break
            except TransientError:
                if request.supports_retry():
                    new_request = request.retry()
                    new_response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if isinstance(response.body, _FILE_TYPES) or \
           IUnboundStreamIterator.providedBy(response.body):
            result = response.body
        else:
            # If somebody used response.write, that data will be in the
            # response.stdout BytesIO, so we put that before the body.
            result = (response.stdout.getvalue(), response.body)

        for func in response.after_list:
            func()

    # Return the result body iterable.
    return result
Пример #30
0
def clear(event):
    """ clear the stored request object """
    clearRequest()
Пример #31
0
                # commit transaction
                transaction.commit()
                return result
            except ConflictError, e:
                # On ZODB conflicts, retry using celery's mechanism
                transaction.abort()
                raise Retry(exc=e)
            except:
                logger.warn('Error running task: %s' % traceback.format_exc())
                transaction.abort()
                raise
        finally:
            noSecurityManager()
            setSite(None)
            self.app._p_jar.close()
            clearRequest()


class AuthorizedFunctionRunner(FunctionRunner):

    def authorize(self):
        if self.eager:
            # ignore, run as current user
            return

        notify(BeforeTraverseEvent(self.site, self.site.REQUEST))
        setSite(self.site)

        # set up user
        # TODO: using plone.api.get_user().getUser()
        # somehow makes the test fail, probably because the whole setRoles
Пример #32
0
def clear(event):
    clearRequest()
Пример #33
0
def publish_module(
        environ,
        start_response,
        _publish=publish,  # only for testing
        _response=None,
        _response_factory=WSGIResponse,
        _request=None,
        _request_factory=WSGIRequest,
        _module_name='Zope2'):
    module_info = get_module_info(_module_name)
    result = ()

    path_info = environ.get('PATH_INFO')
    if path_info and PY3:
        # The WSGI server automatically treats the PATH_INFO as latin-1 encoded
        # bytestrings. Typically this is a false assumption as the browser
        # delivers utf-8 encoded PATH_INFO. We, therefore, need to encode it
        # again with latin-1 to get a utf-8 encoded bytestring.
        path_info = path_info.encode('latin-1')
        # But in Python 3 we need text here, so we decode the bytestring.
        path_info = path_info.decode('utf-8')

        environ['PATH_INFO'] = path_info
    with closing(BytesIO()) as stdout, closing(BytesIO()) as stderr:
        new_response = (_response if _response is not None else
                        _response_factory(stdout=stdout, stderr=stderr))
        new_response._http_version = environ['SERVER_PROTOCOL'].split('/')[1]
        new_response._server_version = environ.get('SERVER_SOFTWARE')

        new_request = (_request if _request is not None else _request_factory(
            environ['wsgi.input'], environ, new_response))

        for i in range(getattr(new_request, 'retry_max_count', 3) + 1):
            request = new_request
            response = new_response
            setRequest(request)
            try:
                with load_app(module_info) as new_mod_info:
                    with transaction_pubevents(request, response):
                        response = _publish(request, new_mod_info)
                break
            except TransientError as exc:
                if request.supports_retry():
                    new_request = request.retry()
                    new_response = new_request.response
                else:
                    raise
            finally:
                request.close()
                clearRequest()

        # Start the WSGI server response
        status, headers = response.finalize()
        start_response(status, headers)

        if (isinstance(response.body, _FILE_TYPES)
                or IUnboundStreamIterator.providedBy(response.body)):
            result = response.body
        else:
            # If somebody used response.write, that data will be in the
            # response.stdout BytesIO, so we put that before the body.
            result = (response.stdout.getvalue(), response.body)

        for func in response.after_list:
            func()

    # Return the result body iterable.
    return result
Пример #34
0
def publish_module_standard(module_name,
                            stdin=sys.stdin,
                            stdout=sys.stdout,
                            stderr=sys.stderr,
                            environ=os.environ,
                            debug=0,
                            request=None,
                            response=None):
    must_die = 0
    status = 200
    after_list = [None]
    try:
        try:
            if response is None:
                response = Response(stdout=stdout, stderr=stderr)
            else:
                stdout = response.stdout

            # debug is just used by tests (has nothing to do with debug_mode!)
            response.handle_errors = not debug

            if request is None:
                request = Request(stdin, environ, response)

            setRequest(request)

            # make sure that the request we hand over has the
            # default layer/skin set on it; subsequent code that
            # wants to look up views will likely depend on it
            if ISkinnable.providedBy(request):
                setDefaultSkin(request)

            response = publish(request, module_name, after_list, debug=debug)
        except (SystemExit, ImportError):
            # XXX: Rendered ImportErrors were never caught here because they
            # were re-raised as string exceptions. Maybe we should handle
            # ImportErrors like all other exceptions. Currently they are not
            # re-raised at all, so they don't show up here.
            must_die = sys.exc_info()
            request.response.exception(1)
        except:
            # debug is just used by tests (has nothing to do with debug_mode!)
            if debug:
                raise
            request.response.exception()
            status = response.getStatus()

        if response:
            outputBody = getattr(response, 'outputBody', None)
            if outputBody is not None:
                outputBody()
            else:
                response = str(response)
                if response:
                    stdout.write(response)

        # The module defined a post-access function, call it
        if after_list[0] is not None:
            after_list[0]()

    finally:
        if request is not None:
            request.close()
            clearRequest()

    if must_die:
        # Try to turn exception value into an exit code.
        try:
            if hasattr(must_die[1], 'code'):
                code = must_die[1].code
            else:
                code = int(must_die[1])
        except:
            code = must_die[1] and 1 or 0
        if hasattr(request.response, '_requestShutdown'):
            request.response._requestShutdown(code)

        try:
            reraise(must_die[0], must_die[1], must_die[2])
        finally:
            must_die = None

    return status
Пример #35
0
 def tearDown(self):
     clearRequest()