Python twisted.web.server.Request() Examples

The following are 30 code examples of twisted.web.server.Request(). 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.server , or try the search function .
Example #1
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_sessionDifferentFromSecureSession(self):
        """
        L{Request.session} and L{Request.secure_session} should be two separate
        sessions with unique ids and different cookies.
        """
        d = DummyChannel()
        d.transport = DummyChannel.SSL()
        request = server.Request(d, 1)
        request.site = server.Site(resource.Resource())
        request.sitepath = []
        secureSession = request.getSession()
        self.assertIsNotNone(secureSession)
        self.addCleanup(secureSession.expire)
        self.assertEqual(request.cookies[0].split(b"=")[0],
                         b"TWISTED_SECURE_SESSION")
        session = request.getSession(forceNotSecure=True)
        self.assertIsNotNone(session)
        self.assertEqual(request.cookies[1].split(b"=")[0], b"TWISTED_SESSION")
        self.addCleanup(session.expire)
        self.assertNotEqual(session.uid, secureSession.uid) 
Example #2
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_processingFailedNoTraceback(self):
        """
        L{Request.processingFailed} when the site has C{displayTracebacks} set
        to C{False} does not write out the failure, but give a generic error
        message.
        """
        d = DummyChannel()
        request = server.Request(d, 1)
        request.site = server.Site(resource.Resource())
        request.site.displayTracebacks = False
        fail = failure.Failure(Exception("Oh no!"))
        request.processingFailed(fail)

        self.assertNotIn(b"Oh no!", request.transport.written.getvalue())
        self.assertIn(
            b"Processing Failed", request.transport.written.getvalue()
        )

        # Since we didn't "handle" the exception, flush it to prevent a test
        # failure
        self.assertEqual(1, len(self.flushLoggedErrors())) 
Example #3
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_processingFailedDisplayTraceback(self):
        """
        L{Request.processingFailed} when the site has C{displayTracebacks} set
        to C{True} writes out the failure.
        """
        d = DummyChannel()
        request = server.Request(d, 1)
        request.site = server.Site(resource.Resource())
        request.site.displayTracebacks = True
        fail = failure.Failure(Exception("Oh no!"))
        request.processingFailed(fail)

        self.assertIn(b"Oh no!", request.transport.written.getvalue())

        # Since we didn't "handle" the exception, flush it to prevent a test
        # failure
        self.assertEqual(1, len(self.flushLoggedErrors())) 
Example #4
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_processingFailedDisplayTracebackHandlesUnicode(self):
        """
        L{Request.processingFailed} when the site has C{displayTracebacks} set
        to C{True} writes out the failure, making UTF-8 items into HTML
        entities.
        """
        d = DummyChannel()
        request = server.Request(d, 1)
        request.site = server.Site(resource.Resource())
        request.site.displayTracebacks = True
        fail = failure.Failure(Exception(u"\u2603"))
        request.processingFailed(fail)

        self.assertIn(b"☃", request.transport.written.getvalue())

        # On some platforms, we get a UnicodeError when trying to
        # display the Failure with twisted.python.log because
        # the default encoding cannot display u"\u2603".  Windows for example
        # uses a default encodig of cp437 which does not support u"\u2603".
        self.flushLoggedErrors(UnicodeError)

        # Since we didn't "handle" the exception, flush it to prevent a test
        # failure
        self.assertEqual(1, len(self.flushLoggedErrors())) 
Example #5
Source File: test_util.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_headersAndCode(self):
        """
        L{redirectTo} will set the C{Location} and C{Content-Type} headers on
        its request, and set the response code to C{FOUND}, so the browser will
        be redirected.
        """
        request = Request(DummyChannel(), True)
        request.method = b'GET'
        targetURL = b"http://target.example.com/4321"
        redirectTo(targetURL, request)
        self.assertEqual(request.code, FOUND)
        self.assertEqual(
            request.responseHeaders.getRawHeaders(b'location'), [targetURL])
        self.assertEqual(
            request.responseHeaders.getRawHeaders(b'content-type'),
            [b'text/html; charset=utf-8']) 
Example #6
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_sessionAttribute(self):
        """
        On a L{Request}, the C{session} attribute retrieves the associated
        L{Session} only if it has been initialized.  If the request is secure,
        it retrieves the secure session.
        """
        site = server.Site(resource.Resource())
        d = DummyChannel()
        d.transport = DummyChannel.SSL()
        request = server.Request(d, 1)
        request.site = site
        request.sitepath = []
        self.assertIs(request.session, None)
        insecureSession = request.getSession(forceNotSecure=True)
        self.addCleanup(insecureSession.expire)
        self.assertIs(request.session, None)
        secureSession = request.getSession()
        self.addCleanup(secureSession.expire)
        self.assertIsNot(secureSession, None)
        self.assertIsNot(secureSession, insecureSession)
        self.assertIs(request.session, secureSession) 
Example #7
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_retrieveNonExistentSession(self):
        """
        L{Request.getSession} generates a new session if the relevant cookie is
        set in the incoming request.
        """
        site = server.Site(resource.Resource())
        d = DummyChannel()
        request = server.Request(d, 1)
        request.site = site
        request.sitepath = []
        request.received_cookies[b'TWISTED_SESSION'] = b"does-not-exist"
        session = request.getSession()
        self.assertIsNotNone(session)
        self.addCleanup(session.expire)
        self.assertTrue(request.cookies[0].startswith(b'TWISTED_SESSION='))
        # It should be a new session ID.
        self.assertNotIn(b"does-not-exist", request.cookies[0]) 
Example #8
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_interfaces(self):
        """
        L{server.GzipEncoderFactory} implements the
        L{iweb._IRequestEncoderFactory} and its C{encoderForRequest} returns an
        instance of L{server._GzipEncoder} which implements
        L{iweb._IRequestEncoder}.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"gzip,deflate"])
        factory = server.GzipEncoderFactory()
        self.assertTrue(verifyObject(iweb._IRequestEncoderFactory, factory))

        encoder = factory.encoderForRequest(request)
        self.assertTrue(verifyObject(iweb._IRequestEncoder, encoder)) 
Example #9
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_multipleAccept(self):
        """
        If there are multiple I{Accept-Encoding} header,
        L{server.GzipEncoderFactory} reads them properly to detect if gzip is
        supported.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"deflate", b"gzip"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertNotIn(b"Content-Length", data)
        self.assertIn(b"Content-Encoding: gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data",
                         zlib.decompress(body, 16 + zlib.MAX_WBITS)) 
Example #10
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_multipleEncodingLines(self):
        """
        If there are several I{Content-Encoding} headers,
        L{server.GzipEncoderFactory} normalizes it and appends gzip to the
        field value.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"deflate", b"gzip"])
        request.responseHeaders.setRawHeaders(b"Content-Encoding",
                                             [b"foo", b"bar"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertNotIn(b"Content-Length", data)
        self.assertIn(b"Content-Encoding: foo,bar,gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data",
                         zlib.decompress(body, 16 + zlib.MAX_WBITS)) 
Example #11
Source File: test_web.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def render(self, resource):
        """
        Render the given resource as a response to this request.

        This implementation only handles a few of the most common behaviors of
        resources.  It can handle a render method that returns a string or
        C{NOT_DONE_YET}.  It doesn't know anything about the semantics of
        request methods (eg HEAD) nor how to set any particular headers.
        Basically, it's largely broken, but sufficient for some tests at least.
        It should B{not} be expanded to do all the same stuff L{Request} does.
        Instead, L{DummyRequest} should be phased out and L{Request} (or some
        other real code factored in a different way) used.
        """
        result = resource.render(self)
        if result is server.NOT_DONE_YET:
            return
        self.write(result)
        self.finish() 
Example #12
Source File: test_util.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_headersAndCode(self):
        """
        L{redirectTo} will set the C{Location} and C{Content-Type} headers on
        its request, and set the response code to C{FOUND}, so the browser will
        be redirected.
        """
        request = Request(DummyChannel(), True)
        request.method = b'GET'
        targetURL = b"http://target.example.com/4321"
        redirectTo(targetURL, request)
        self.assertEqual(request.code, FOUND)
        self.assertEqual(
            request.responseHeaders.getRawHeaders(b'location'), [targetURL])
        self.assertEqual(
            request.responseHeaders.getRawHeaders(b'content-type'),
            [b'text/html; charset=utf-8']) 
Example #13
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testSimple(self):
        """
        The path component of the root URL of a L{server.Site} whose
        root resource is below C{/} is that resource's path, and the
        netloc component is the L{site.Server}'s own host and port.
        """
        r = resource.Resource()
        r.isLeaf = 0
        rr = RootResource()
        r.putChild(b'foo', rr)
        rr.putChild(b'', rr)
        rr.putChild(b'bar', resource.Resource())
        chan = self.createServer(r)
        for url in [b'/foo/', b'/foo/bar', b'/foo/bar/baz', b'/foo/bar/']:
            request = server.Request(chan, 1)
            request.setHost(b'example.com', 81)
            request.gotLength(0)
            request.requestReceived(b'GET', url, b'HTTP/1.0')
            self.assertEqual(request.getRootURL(),
                             b"http://example.com:81/foo") 
Example #14
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_alreadyEncoded(self):
        """
        If the content is already encoded and the I{Content-Encoding} header is
        set, L{server.GzipEncoderFactory} properly appends gzip to it.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"deflate", b"gzip"])
        request.responseHeaders.setRawHeaders(b"Content-Encoding",
                                             [b"deflate"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertNotIn(b"Content-Length", data)
        self.assertIn(b"Content-Encoding: deflate,gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data",
                         zlib.decompress(body, 16 + zlib.MAX_WBITS)) 
Example #15
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_sessionAttribute(self):
        """
        On a L{Request}, the C{session} attribute retrieves the associated
        L{Session} only if it has been initialized.  If the request is secure,
        it retrieves the secure session.
        """
        site = server.Site(resource.Resource())
        d = DummyChannel()
        d.transport = DummyChannel.SSL()
        request = server.Request(d, 1)
        request.site = site
        request.sitepath = []
        self.assertIs(request.session, None)
        insecureSession = request.getSession(forceNotSecure=True)
        self.addCleanup(insecureSession.expire)
        self.assertIs(request.session, None)
        secureSession = request.getSession()
        self.addCleanup(secureSession.expire)
        self.assertIsNot(secureSession, None)
        self.assertIsNot(secureSession, insecureSession)
        self.assertIs(request.session, secureSession) 
Example #16
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_rejectNonOPTIONSStar(self):
        """
        L{Request} handles any non-OPTIONS verb requesting the * path by doing
        a fast-return 405 Method Not Allowed, indicating only the support for
        OPTIONS.
        """
        d = DummyChannel()
        request = server.Request(d, 1)
        request.setHost(b'example.com', 80)
        request.gotLength(0)
        request.requestReceived(b'GET', b'*', b'HTTP/1.1')

        response = d.transport.written.getvalue()
        self.assertTrue(
            response.startswith(b'HTTP/1.1 405 Method Not Allowed')
        )
        self.assertIn(b'Content-Length: 0\r\n', response)
        self.assertIn(b'Allow: OPTIONS\r\n', response) 
Example #17
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_noDefaultContentTypeOnZeroLengthResponse(self):
        """
        Responses with no length do not have a default content-type applied.
        """
        resrc = ZeroLengthResource()
        resrc.putChild(b'', resrc)
        site = server.Site(resrc)
        d = DummyChannel()
        d.site = site
        request = server.Request(d, 1)
        request.site = site
        request.setHost(b'example.com', 80)
        request.gotLength(0)
        request.requestReceived(b'GET', b'/', b'HTTP/1.1')

        self.assertNotIn(
            b'content-type', request.transport.written.getvalue().lower()
        ) 
Example #18
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_noDefaultContentTypeOn204Response(self):
        """
        Responses with a 204 status code have no default content-type applied.
        """
        resrc = NoContentResource()
        resrc.putChild(b'', resrc)
        site = server.Site(resrc)
        d = DummyChannel()
        d.site = site
        request = server.Request(d, 1)
        request.site = site
        request.setHost(b'example.com', 80)
        request.gotLength(0)
        request.requestReceived(b'GET', b'/', b'HTTP/1.1')

        response = request.transport.written.getvalue()
        self.assertTrue(response.startswith(b'HTTP/1.1 204 No Content\r\n'))
        self.assertNotIn(b'content-type', response.lower()) 
Example #19
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_encoding(self):
        """
        If the client request passes a I{Accept-Encoding} header which mentions
        gzip, L{server._GzipEncoder} automatically compresses the data.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"gzip,deflate"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertNotIn(b"Content-Length", data)
        self.assertIn(b"Content-Encoding: gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data",
                          zlib.decompress(body, 16 + zlib.MAX_WBITS)) 
Example #20
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_whitespaceInAcceptEncoding(self):
        """
        If the client request passes a I{Accept-Encoding} header which mentions
        gzip, with whitespace inbetween the encoding name and the commas,
        L{server._GzipEncoder} automatically compresses the data.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"deflate, gzip"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertNotIn(b"Content-Length", data)
        self.assertIn(b"Content-Encoding: gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data",
                          zlib.decompress(body, 16 + zlib.MAX_WBITS)) 
Example #21
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_multipleAccept(self):
        """
        If there are multiple I{Accept-Encoding} header,
        L{server.GzipEncoderFactory} reads them properly to detect if gzip is
        supported.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"deflate", b"gzip"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertNotIn(b"Content-Length", data)
        self.assertIn(b"Content-Encoding: gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data",
                         zlib.decompress(body, 16 + zlib.MAX_WBITS)) 
Example #22
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_alreadyEncoded(self):
        """
        If the content is already encoded and the I{Content-Encoding} header is
        set, L{server.GzipEncoderFactory} properly appends gzip to it.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"deflate", b"gzip"])
        request.responseHeaders.setRawHeaders(b"Content-Encoding",
                                             [b"deflate"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertNotIn(b"Content-Length", data)
        self.assertIn(b"Content-Encoding: deflate,gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data",
                         zlib.decompress(body, 16 + zlib.MAX_WBITS)) 
Example #23
Source File: test_web.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def testRoot(self):
        """
        The path component of the root URL of a L{server.Site} whose
        root resource is at C{/} is C{/}, and the netloc component is
        the L{site.Server}'s own host and port.
        """
        rr = RootResource()
        rr.putChild(b'', rr)
        rr.putChild(b'bar', resource.Resource())
        chan = self.createServer(rr)
        for url in [b'/', b'/bar', b'/bar/baz', b'/bar/']:
            request = server.Request(chan, 1)
            request.setHost(b'example.com', 81)
            request.gotLength(0)
            request.requestReceived(b'GET', url, b'HTTP/1.0')
            self.assertEqual(request.getRootURL(),
                             b"http://example.com:81/") 
Example #24
Source File: test_web.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_retrieveExistingSession(self):
        """
        L{Request.getSession} retrieves an existing session if the relevant
        cookie is set in the incoming request.
        """
        site = server.Site(resource.Resource())
        d = DummyChannel()
        request = server.Request(d, 1)
        request.site = site
        request.sitepath = []
        mySession = server.Session(b"special-id", site)
        site.sessions[mySession.uid] = mySession
        request.received_cookies[b'TWISTED_SESSION'] = mySession.uid
        self.assertIs(request.getSession(), mySession) 
Example #25
Source File: test_web.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_nonEncoding(self):
        """
        L{server.GzipEncoderFactory} doesn't return a L{server._GzipEncoder} if
        the I{Accept-Encoding} header doesn't mention gzip support.
        """
        request = server.Request(self.channel, False)
        request.gotLength(0)
        request.requestHeaders.setRawHeaders(b"Accept-Encoding",
                                             [b"foo,bar"])
        request.requestReceived(b'GET', b'/foo', b'HTTP/1.0')
        data = self.channel.transport.written.getvalue()
        self.assertIn(b"Content-Length", data)
        self.assertNotIn(b"Content-Encoding: gzip\r\n", data)
        body = data[data.find(b"\r\n\r\n") + 4:]
        self.assertEqual(b"Some data", body) 
Example #26
Source File: test_web.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testSimple(self):
        r = resource.Resource()
        r.isLeaf=0
        rr = RootResource()
        r.putChild('foo', rr)
        rr.putChild('', rr)
        rr.putChild('bar', resource.Resource())
        chan = self.createServer(r)
        for url in ['/foo/', '/foo/bar', '/foo/bar/baz', '/foo/bar/']:
            request = server.Request(chan, 1)
            request.setHost('example.com', 81)
            request.gotLength(0)
            request.requestReceived('GET', url, 'HTTP/1.0')
            self.assertEqual(request.getRootURL(), "http://example.com/foo") 
Example #27
Source File: test_web.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testRoot(self):
        rr = RootResource()
        rr.putChild('', rr)
        rr.putChild('bar', resource.Resource())
        chan = self.createServer(rr)
        for url in ['/', '/bar', '/bar/baz', '/bar/']:
            request = server.Request(chan, 1)
            request.setHost('example.com', 81)
            request.gotLength(0)
            request.requestReceived('GET', url, 'HTTP/1.0')
            self.assertEqual(request.getRootURL(), "http://example.com/") 
Example #28
Source File: test_web.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _getReq(self):
        d = DummyChannel()
        d.site.resource.putChild('newrender', NewRenderResource())
        d.transport.port = 81
        request = server.Request(d, 1)
        request.setHost('example.com', 81)
        request.gotLength(0)
        return request 
Example #29
Source File: test_woven.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kw):
        server.Request.__init__(self, *args, **kw)
        self._cookieCache = {}
        from cStringIO import StringIO
        self.content = StringIO()
        self.received_headers['host'] = 'fake.com'
        self.written = StringIO() 
Example #30
Source File: test_web.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testPrePathURLHTTPPortAndSSL(self):
        d = DummyChannel()
        d.transport = DummyChannel.SSL()
        d.transport.port = 80
        request = server.Request(d, 1)
        request.setHost('example.com', 80)
        request.gotLength(0)
        request.requestReceived('GET', '/foo/bar', 'HTTP/1.0')
        self.assertEqual(request.prePathURL(), 'https://example.com:80/foo/bar')