Python twisted.web.resource.getChildForRequest() Examples

The following are 30 code examples of twisted.web.resource.getChildForRequest(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.web.resource , or try the search function .
Example #1
Source File: test_httpauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_anonymousAccess(self):
        """
        Anonymous requests are allowed if a L{Portal} has an anonymous checker
        registered.
        """
        unprotectedContents = "contents of the unprotected child resource"

        self.avatars[ANONYMOUS] = Resource()
        self.avatars[ANONYMOUS].putChild(
            self.childName, Data(unprotectedContents, 'text/plain'))
        self.portal.registerChecker(AllowAnonymousAccess())

        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEquals(request.written, [unprotectedContents])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #2
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_directoryWithoutTrailingSlashRedirects(self):
        """
        A request for a path which is a directory but does not have a trailing
        slash will be redirected to a URL which does have a slash by L{File}.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child('folder').makedirs()
        file = static.File(base.path)

        request = DummyRequest([b"folder"])
        request.uri = b"http://dummy/folder#baz?foo=bar"
        child = resource.getChildForRequest(file, request)

        self.successResultOf(self._render(child, request))
        self.assertEqual(request.responseCode, FOUND)
        self.assertEqual(request.responseHeaders.getRawHeaders(b"location"),
                         [b"http://dummy/folder/#baz?foo=bar"]) 
Example #3
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_ignoredExtensionsIgnored(self):
        """
        A request for the I{base} child of a L{File} succeeds with a resource
        for the I{base<extension>} file in the path the L{File} was created
        with if such a file exists and the L{File} has been configured to
        ignore the I{<extension>} extension.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child('foo.bar').setContent(b'baz')
        base.child('foo.quux').setContent(b'foobar')
        file = static.File(base.path, ignoredExts=(".bar",))

        request = DummyRequest([b"foo"])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(b''.join(request.written), b'baz')
        d.addCallback(cbRendered)
        return d 
Example #4
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_staticFile(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which names a file in the path the L{File} was created with, that file
        is served as the response to the request.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child("foo.bar").setContent(b"baz")
        file = static.File(base.path)

        request = DummyRequest([b'foo.bar'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(b''.join(request.written), b'baz')
            self.assertEqual(
                request.responseHeaders.getRawHeaders(b'content-length')[0],
                b'3')
        d.addCallback(cbRendered)
        return d 
Example #5
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_indexNames(self):
        """
        If a request is made which encounters a L{File} before a final empty
        segment, a file in the L{File} instance's C{indexNames} list which
        exists in the path the L{File} was created with is served as the
        response to the request.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child("foo.bar").setContent(b"baz")
        file = static.File(base.path)
        file.indexNames = ['foo.bar']

        request = DummyRequest([b''])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(b''.join(request.written), b'baz')
            self.assertEqual(
                request.responseHeaders.getRawHeaders(b'content-length')[0],
                b'3')
        d.addCallback(cbRendered)
        return d 
Example #6
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_undecodablePath(self):
        """
        A request whose path cannot be decoded as UTF-8 receives a not
        found response, and the failure is logged.
        """
        path = self.mktemp()
        if isinstance(path, bytes):
            path = path.decode('ascii')
        base = FilePath(path)
        base.makedirs()

        file = static.File(base.path)
        request = DummyRequest([b"\xff"])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, 404)
            self.assertEqual(len(self.flushLoggedErrors(UnicodeDecodeError)),
                             1)
        d.addCallback(cbRendered)
        return d 
Example #7
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_securityViolationNotFound(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which cannot be looked up in the filesystem due to security
        considerations, a not found response is sent.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        file = static.File(base.path)

        request = DummyRequest([b'..'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, 404)
        d.addCallback(cbRendered)
        return d 
Example #8
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_emptyChildUnicodeParent(self):
        """
        The C{u''} child of a L{File} which corresponds to a directory
        whose path is text is a L{DirectoryLister} that renders to a
        binary listing.

        @see: U{https://twistedmatrix.com/trac/ticket/9438}
        """
        textBase = FilePath(self.mktemp()).asTextMode()
        textBase.makedirs()
        textBase.child(u"text-file").open('w').close()
        textFile = static.File(textBase.path)

        request = DummyRequest([b''])
        child = resource.getChildForRequest(textFile, request)
        self.assertIsInstance(child, static.DirectoryLister)

        nativePath = compat.nativeString(textBase.path)
        self.assertEqual(child.path, nativePath)

        response = child.render(request)
        self.assertIsInstance(response, bytes) 
Example #9
Source File: test_static.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_notFound(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which does not correspond to any file in the path the L{File} was
        created with, a not found response is sent.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        file = static.File(base.path)

        request = DummyRequest([b'foobar'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, 404)
        d.addCallback(cbRendered)
        return d 
Example #10
Source File: test_httpauth.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_anonymousAccess(self):
        """
        Anonymous requests are allowed if a L{Portal} has an anonymous checker
        registered.
        """
        unprotectedContents = b"contents of the unprotected child resource"

        self.avatars[ANONYMOUS] = Resource()
        self.avatars[ANONYMOUS].putChild(
            self.childName, Data(unprotectedContents, 'text/plain'))
        self.portal.registerChecker(AllowAnonymousAccess())

        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEqual(request.written, [unprotectedContents])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #11
Source File: test_httpauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def _invalidAuthorizationTest(self, response):
        """
        Create a request with the given value as the value of an
        I{Authorization} header and perform resource traversal with it,
        starting at C{self.wrapper}.  Assert that the result is a 401 response
        code.  Return a L{Deferred} which fires when this is all done.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        request.headers['authorization'] = response
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()
        def cbFinished(result):
            self.assertEqual(request.responseCode, 401)
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #12
Source File: test_httpauth.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_unexpectedDecodeError(self):
        """
        Any unexpected exception raised by the credential factory's C{decode}
        method results in a 500 response code and causes the exception to be
        logged.
        """
        class UnexpectedException(Exception):
            pass

        class BadFactory(object):
            scheme = 'bad'

            def getChallenge(self, client):
                return {}

            def decode(self, response, request):
                raise UnexpectedException()

        self.credentialFactories.append(BadFactory())
        request = self.makeRequest([self.childName])
        request.headers['authorization'] = 'Bad abc'
        child = getChildForRequest(self.wrapper, request)
        request.render(child)
        self.assertEqual(request.responseCode, 500)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) 
Example #13
Source File: test_static.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_notFound(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which does not correspond to any file in the path the L{File} was
        created with, a not found response is sent.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        file = static.File(base.path)

        request = DummyRequest(['foobar'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, 404)
        d.addCallback(cbRendered)
        return d 
Example #14
Source File: test_static.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_ignoredExtensionsIgnored(self):
        """
        A request for the I{base} child of a L{File} succeeds with a resource
        for the I{base<extension>} file in the path the L{File} was created
        with if such a file exists and the L{File} has been configured to
        ignore the I{<extension>} extension.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child('foo.bar').setContent(b'baz')
        base.child('foo.quux').setContent(b'foobar')
        file = static.File(base.path, ignoredExts=(b".bar",))

        request = DummyRequest([b"foo"])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(b''.join(request.written), b'baz')
        d.addCallback(cbRendered)
        return d 
Example #15
Source File: test_static.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_staticFile(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which names a file in the path the L{File} was created with, that file
        is served as the response to the request.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child("foo.bar").setContent(b"baz")
        file = static.File(base.path)

        request = DummyRequest([b'foo.bar'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(b''.join(request.written), b'baz')
            self.assertEqual(
                request.responseHeaders.getRawHeaders(b'content-length')[0],
                b'3')
        d.addCallback(cbRendered)
        return d 
Example #16
Source File: app_test_client.py    From pixelated-user-agent with GNU Affero General Public License v3.0 6 votes vote down vote up
def _render(self, request, as_json=True):
        def get_str(_str):
            return json.loads(_str) if as_json else _str

        def get_request_written_data(_=None):
            written_data = request.getWrittenData()
            if written_data:
                return get_str(written_data)

        resource = getChildForRequest(self.resource, request)
        result = resource.render(request)

        if isinstance(result, basestring):
            return get_str(result), request

        # result is NOT_DONE_YET
        d = succeed(request) if request.finished else request.notifyFinish()
        d.addCallback(get_request_written_data)
        return d, request 
Example #17
Source File: test_static.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_indexNames(self):
        """
        If a request is made which encounters a L{File} before a final empty
        segment, a file in the L{File} instance's C{indexNames} list which
        exists in the path the L{File} was created with is served as the
        response to the request.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child("foo.bar").setContent(b"baz")
        file = static.File(base.path)
        file.indexNames = [b'foo.bar']

        request = DummyRequest([b''])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(b''.join(request.written), b'baz')
            self.assertEqual(
                request.responseHeaders.getRawHeaders(b'content-length')[0],
                b'3')
        d.addCallback(cbRendered)
        return d 
Example #18
Source File: test_static.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_securityViolationNotFound(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which cannot be looked up in the filesystem due to security
        considerations, a not found response is sent.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        file = static.File(base.path)

        request = DummyRequest([b'..'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, 404)
        d.addCallback(cbRendered)
        return d 
Example #19
Source File: test_static.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_ignoredExtensionsIgnored(self):
        """
        A request for the I{base} child of a L{File} succeeds with a resource
        for the I{base<extension>} file in the path the L{File} was created
        with if such a file exists and the L{File} has been configured to
        ignore the I{<extension>} extension.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child('foo.bar').setContent('baz')
        base.child('foo.quux').setContent('foobar')
        file = static.File(base.path, ignoredExts=(".bar",))

        request = DummyRequest(["foo"])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(''.join(request.written), 'baz')
        d.addCallback(cbRendered)
        return d 
Example #20
Source File: test_static.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_processors(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which names a file with an extension which is in the L{File}'s
        C{processors} mapping, the processor associated with that extension is
        used to serve the response to the request.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child("foo.bar").setContent(
            "from twisted.web.static import Data\n"
            "resource = Data('dynamic world','text/plain')\n")

        file = static.File(base.path)
        file.processors = {'.bar': script.ResourceScript}
        request = DummyRequest(["foo.bar"])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(''.join(request.written), 'dynamic world')
            self.assertEqual(request.outgoingHeaders['content-length'], '13')
        d.addCallback(cbRendered)
        return d 
Example #21
Source File: test_static.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_indexNames(self):
        """
        If a request is made which encounters a L{File} before a final empty
        segment, a file in the L{File} instance's C{indexNames} list which
        exists in the path the L{File} was created with is served as the
        response to the request.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child("foo.bar").setContent("baz")
        file = static.File(base.path)
        file.indexNames = ['foo.bar']

        request = DummyRequest([''])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(''.join(request.written), 'baz')
            self.assertEqual(request.outgoingHeaders['content-length'], '3')
        d.addCallback(cbRendered)
        return d 
Example #22
Source File: test_static.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_notFound(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which does not correspond to any file in the path the L{File} was
        created with, a not found response is sent.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        file = static.File(base.path)

        request = DummyRequest([b'foobar'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, 404)
        d.addCallback(cbRendered)
        return d 
Example #23
Source File: test_httpauth.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_anonymousAccess(self):
        """
        Anonymous requests are allowed if a L{Portal} has an anonymous checker
        registered.
        """
        unprotectedContents = b"contents of the unprotected child resource"

        self.avatars[ANONYMOUS] = Resource()
        self.avatars[ANONYMOUS].putChild(
            self.childName, Data(unprotectedContents, 'text/plain'))
        self.portal.registerChecker(AllowAnonymousAccess())

        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = getChildForRequest(self.wrapper, request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEqual(request.written, [unprotectedContents])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #24
Source File: test_httpauth.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_unexpectedDecodeError(self):
        """
        Any unexpected exception raised by the credential factory's C{decode}
        method results in a 500 response code and causes the exception to be
        logged.
        """
        class UnexpectedException(Exception):
            pass

        class BadFactory(object):
            scheme = b'bad'

            def getChallenge(self, client):
                return {}

            def decode(self, response, request):
                raise UnexpectedException()

        self.credentialFactories.append(BadFactory())
        request = self.makeRequest([self.childName])
        request.requestHeaders.addRawHeader(b'authorization', b'Bad abc')
        child = getChildForRequest(self.wrapper, request)
        request.render(child)
        self.assertEqual(request.responseCode, 500)
        self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) 
Example #25
Source File: test_static.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_staticFile(self):
        """
        If a request is made which encounters a L{File} before a final segment
        which names a file in the path the L{File} was created with, that file
        is served as the response to the request.
        """
        base = FilePath(self.mktemp())
        base.makedirs()
        base.child("foo.bar").setContent("baz")
        file = static.File(base.path)

        request = DummyRequest(['foo.bar'])
        child = resource.getChildForRequest(file, request)

        d = self._render(child, request)
        def cbRendered(ignored):
            self.assertEqual(''.join(request.written), 'baz')
            self.assertEqual(request.outgoingHeaders['content-length'], '3')
        d.addCallback(cbRendered)
        return d 
Example #26
Source File: server.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getResourceFor(self, request):
        """
        Get a resource for a request.

        This iterates through the resource heirarchy, calling
        getChildWithDefault on each resource it finds for a path element,
        stopping when it hits an element where isLeaf is true.
        """
        request.site = self
        # Sitepath is used to determine cookie names between distributed
        # servers and disconnected sites.
        request.sitepath = copy.copy(request.prepath)
        return resource.getChildForRequest(self.resource, request) 
Example #27
Source File: server.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def getResourceFor(self, request):
        """
        Get a resource for a request.

        This iterates through the resource hierarchy, calling
        getChildWithDefault on each resource it finds for a path element,
        stopping when it hits an element where isLeaf is true.
        """
        request.site = self
        # Sitepath is used to determine cookie names between distributed
        # servers and disconnected sites.
        request.sitepath = copy.copy(request.prepath)
        return resource.getChildForRequest(self.resource, request)

    # IProtocolNegotiationFactory 
Example #28
Source File: test_static.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_childrenNotFound(self):
        """
        Any child resource of L{static.DirectoryLister} renders an HTTP
        I{NOT FOUND} response code.
        """
        path = FilePath(self.mktemp())
        path.makedirs()
        lister = static.DirectoryLister(path.path)
        request = self._request(b'')
        child = resource.getChildForRequest(lister, request)
        result = _render(child, request)
        def cbRendered(ignored):
            self.assertEqual(request.responseCode, http.NOT_FOUND)
        result.addCallback(cbRendered)
        return result 
Example #29
Source File: test_static.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_childrenNotFound(self):
        """
        Any child resource of L{static.DirectoryLister} renders an HTTP
        I{NOT FOUND} response code.
        """
        path = FilePath(self.mktemp())
        path.makedirs()
        lister = static.DirectoryLister(path.path)
        request = self._request('')
        child = resource.getChildForRequest(lister, request)
        result = _render(child, request)
        def cbRendered(ignored):
            self.assertEquals(request.responseCode, http.NOT_FOUND)
        result.addCallback(cbRendered)
        return result 
Example #30
Source File: util.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _cbChild(self, child, request):
        request.render(resource.getChildForRequest(child, request))