Python twisted.web.resource.Resource() Examples

The following are 30 code examples of twisted.web.resource.Resource(). 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: site.py    From worker with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, db):
        self.prefix = ""
        root = Resource()
        prefix = root
        for path in config.PREFIX.split('/'):
            if len(path):
                r = Resource()
                prefix.putChild(path, r)
                prefix = r
                self.prefix += "/%s" % path
        prefix.putChild("trigger", Triggers(db))
        prefix.putChild("tag", Tags(db))
        prefix.putChild("pattern", Patterns(db))
        prefix.putChild("event", Events(db))
        prefix.putChild("contact", Contacts(db))
        prefix.putChild("subscription", Subscriptions(db))
        prefix.putChild("user", Login(db))
        prefix.putChild("notification", Notifications(db))
        server.Site.__init__(self, root) 
Example #2
Source File: rewrite.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def alias(aliasPath, sourcePath):
    """
    I am not a very good aliaser. But I'm the best I can be. If I'm
    aliasing to a Resource that generates links, and it uses any parts
    of request.prepath to do so, the links will not be relative to the
    aliased path, but rather to the aliased-to path. That I can't
    alias static.File directory listings that nicely. However, I can
    still be useful, as many resources will play nice.
    """
    sourcePath = sourcePath.split('/')
    aliasPath = aliasPath.split('/')
    def rewriter(request):
        if request.postpath[:len(aliasPath)] == aliasPath:
            after = request.postpath[len(aliasPath):]
            request.postpath = sourcePath + after
            request.path = '/'+'/'.join(request.prepath+request.postpath)
    return rewriter 
Example #3
Source File: test_distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testDistrib(self):
        # site1 is the publisher
        r1 = resource.Resource()
        r1.putChild("there", static.Data("root", "text/plain"))
        site1 = server.Site(r1)
        self.f1 = PBServerFactory(distrib.ResourcePublisher(site1))
        self.port1 = reactor.listenTCP(0, self.f1)
        self.sub = distrib.ResourceSubscription("127.0.0.1",
                                                self.port1.getHost().port)
        r2 = resource.Resource()
        r2.putChild("here", self.sub)
        f2 = MySite(r2)
        self.port2 = reactor.listenTCP(0, f2)
        agent = client.Agent(reactor)
        d = agent.request(b"GET", "http://127.0.0.1:%d/here/there" % \
                          (self.port2.getHost().port,))
        d.addCallback(client.readBody)
        d.addCallback(self.assertEqual, 'root')
        return d 
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_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 #5
Source File: test_script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_render(self):
        """
        L{ResourceScriptDirectory.getChild} returns a resource which renders a
        response with the HTTP 200 status code and the content of the rpy's
        C{request} global.
        """
        tmp = FilePath(self.mktemp())
        tmp.makedirs()
        tmp.child("test.rpy").setContent(b"""
from twisted.web.resource import Resource
class TestResource(Resource):
    isLeaf = True
    def render_GET(self, request):
        return b'ok'
resource = TestResource()""")
        resource = ResourceScriptDirectory(tmp._asBytesPath())
        request = DummyRequest([b''])
        child = resource.getChild(b"test.rpy", request)
        d = _render(child, request)
        def cbRendered(ignored):
            self.assertEqual(b"".join(request.written), b"ok")
        d.addCallback(cbRendered)
        return d 
Example #6
Source File: test_distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_requestHeaders(self):
        """
        The request headers are available on the request object passed to a
        distributed resource's C{render} method.
        """
        requestHeaders = {}

        class ReportRequestHeaders(resource.Resource):
            def render(self, request):
                requestHeaders.update(dict(
                    request.requestHeaders.getAllRawHeaders()))
                return ""

        request = self._requestTest(
            ReportRequestHeaders(), headers=Headers({'foo': ['bar']}))
        def cbRequested(result):
            self.assertEqual(requestHeaders['Foo'], ['bar'])
        request.addCallback(cbRequested)
        return request 
Example #7
Source File: test_distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_requestResponseCode(self):
        """
        The response code can be set by the request object passed to a
        distributed resource's C{render} method.
        """
        class SetResponseCode(resource.Resource):
            def render(self, request):
                request.setResponseCode(200)
                return ""

        request = self._requestAgentTest(SetResponseCode())
        def cbRequested(result):
            self.assertEqual(result[0].data, "")
            self.assertEqual(result[1].code, 200)
            self.assertEqual(result[1].phrase, "OK")
        request.addCallback(cbRequested)
        return request 
Example #8
Source File: test_distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_requestResponseCodeMessage(self):
        """
        The response code and message can be set by the request object passed to
        a distributed resource's C{render} method.
        """
        class SetResponseCode(resource.Resource):
            def render(self, request):
                request.setResponseCode(200, "some-message")
                return ""

        request = self._requestAgentTest(SetResponseCode())
        def cbRequested(result):
            self.assertEqual(result[0].data, "")
            self.assertEqual(result[1].code, 200)
            self.assertEqual(result[1].phrase, "some-message")
        request.addCallback(cbRequested)
        return request 
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_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 #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_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 #11
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 #12
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 #13
Source File: test_httpauth.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_getChildWithDefaultAuthorized(self):
        """
        Resource traversal which encounters an L{HTTPAuthSessionWrapper}
        results in an L{IResource} which renders the L{IResource} avatar
        retrieved from the portal when the request has a valid I{Authorization}
        header.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        request = self.makeRequest([self.childName])
        child = self._authorizedBasicLogin(request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEqual(request.written, [self.childContent])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #14
Source File: test_httpauth.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_renderAuthorized(self):
        """
        Resource traversal which terminates at an L{HTTPAuthSessionWrapper}
        and includes correct authentication headers results in the
        L{IResource} avatar (not one of its children) retrieved from the
        portal being rendered.
        """
        self.credentialFactories.append(BasicCredentialFactory('example.com'))
        # Request it exactly, not any of its children.
        request = self.makeRequest([])
        child = self._authorizedBasicLogin(request)
        d = request.notifyFinish()
        def cbFinished(ignored):
            self.assertEqual(request.written, [self.avatarContent])
        d.addCallback(cbFinished)
        request.render(child)
        return d 
Example #15
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 #16
Source File: script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def ResourceScript(path, registry):
    """
    I am a normal py file which must define a 'resource' global, which should
    be an instance of (a subclass of) web.resource.Resource; it will be
    renderred.
    """
    cs = CacheScanner(path, registry)
    glob = {'__file__': _coerceToFilesystemEncoding("", path),
            'resource': noRsrc,
            'registry': registry,
            'cache': cs.cache,
            'recache': cs.recache}
    try:
        execfile(path, glob, glob)
    except AlreadyCached as ac:
        return ac.args[0]
    rsrc = glob['resource']
    if cs.doCache and rsrc is not noRsrc:
        registry.cachePath(path, rsrc)
    return rsrc 
Example #17
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_sessionUIDGeneration(self):
        """
        L{site.getSession} generates L{Session} objects with distinct UIDs from
        a secure source of entropy.
        """
        site = server.Site(resource.Resource())
        # Ensure that we _would_ use the unpredictable random source if the
        # test didn't stub it.
        self.assertIdentical(site._entropy, os.urandom)

        def predictableEntropy(n):
            predictableEntropy.x += 1
            return (unichr(predictableEntropy.x) * n).encode("charmap")
        predictableEntropy.x = 0
        self.patch(site, "_entropy", predictableEntropy)
        a = self.getAutoExpiringSession(site)
        b = self.getAutoExpiringSession(site)
        self.assertEqual(a.uid, b"01" * 0x20)
        self.assertEqual(b.uid, b"02" * 0x20)
        # This functionality is silly (the value is no longer used in session
        # generation), but 'counter' was a public attribute since time
        # immemorial so we should make sure if anyone was using it to get site
        # metrics or something it keeps working.
        self.assertEqual(site.counter, 2) 
Example #18
Source File: script.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def ResourceScript(path, registry):
    """
    I am a normal py file which must define a 'resource' global, which should
    be an instance of (a subclass of) web.resource.Resource; it will be
    renderred.
    """
    cs = CacheScanner(path, registry)
    glob = {'__file__': _coerceToFilesystemEncoding("", path),
            'resource': noRsrc,
            'registry': registry,
            'cache': cs.cache,
            'recache': cs.recache}
    try:
        execfile(path, glob, glob)
    except AlreadyCached as ac:
        return ac.args[0]
    rsrc = glob['resource']
    if cs.doCache and rsrc is not noRsrc:
        registry.cachePath(path, rsrc)
    return rsrc 
Example #19
Source File: TTwisted.py    From Aditmadzs2 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, processor, inputProtocolFactory,
                 outputProtocolFactory=None):
        resource.Resource.__init__(self)
        self.inputProtocolFactory = inputProtocolFactory
        if outputProtocolFactory is None:
            self.outputProtocolFactory = inputProtocolFactory
        else:
            self.outputProtocolFactory = outputProtocolFactory
        self.processor = processor 
Example #20
Source File: _http.py    From txacme with MIT License 5 votes vote down vote up
def __init__(self):
        self.resource = Resource() 
Example #21
Source File: test_challenges.py    From txacme with MIT License 5 votes vote down vote up
def test_start_responding(self, token):
        """
        Calling ``start_responding`` makes an appropriate resource available.
        """
        challenge = challenges.HTTP01(token=token)
        response = challenge.response(RSA_KEY_512)

        responder = HTTP01Responder()

        challenge_resource = Resource()
        challenge_resource.putChild(b'acme-challenge', responder.resource)
        root = Resource()
        root.putChild(b'.well-known', challenge_resource)
        client = StubTreq(root)

        encoded_token = challenge.encode('token')
        challenge_url = URL(host=u'example.com', path=[
            u'.well-known', u'acme-challenge', encoded_token]).asText()

        self.assertThat(client.get(challenge_url),
                        succeeded(MatchesStructure(code=Equals(404))))

        responder.start_responding(u'example.com', challenge, response)
        self.assertThat(client.get(challenge_url), succeeded(MatchesAll(
            MatchesStructure(
                code=Equals(200),
                headers=AfterPreprocessing(
                    methodcaller('getRawHeaders', b'content-type'),
                    Equals([b'text/plain']))),
            AfterPreprocessing(methodcaller('content'), succeeded(
                Equals(response.key_authorization.encode('utf-8'))))
        )))

        # Starting twice before stopping doesn't break things
        responder.start_responding(u'example.com', challenge, response)
        self.assertThat(client.get(challenge_url),
                        succeeded(MatchesStructure(code=Equals(200))))

        responder.stop_responding(u'example.com', challenge, response)
        self.assertThat(client.get(challenge_url),
                        succeeded(MatchesStructure(code=Equals(404)))) 
Example #22
Source File: test_client.py    From txacme with MIT License 5 votes vote down vote up
def _create_responder(self):
        action = start_action(action_type=u'integration:create_responder')
        with action.context():
            responder = TLSSNI01Responder()
            host_map = responder.wrap_host_map({})
            site = Site(Resource())
            endpoint = TLSEndpoint(
                endpoint=serverFromString(reactor, self.ENDPOINT),
                contextFactory=SNIMap(host_map))
            return (
                DeferredContext(endpoint.listen(site))
                .addCallback(lambda port: self.addCleanup(port.stopListening))
                .addCallback(lambda _: responder)
                .addActionFinish()) 
Example #23
Source File: twisted_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def start_twisted_server(self):
        class HelloResource(Resource):
            isLeaf = True

            def render_GET(self, request):
                return "Hello from twisted!"
        site = Site(HelloResource())
        port = self.reactor.listenTCP(0, site, interface='127.0.0.1')
        self.twisted_port = port.getHost().port 
Example #24
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, contentType=None):
        resource.Resource.__init__(self)
        self._contentType = contentType 
Example #25
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_makeSession(self):
        """
        L{site.getSession} generates a new C{Session} instance with an uid of
        type L{bytes}.
        """
        site = server.Site(resource.Resource())
        session = self.getAutoExpiringSession(site)

        self.assertIsInstance(session, server.Session)
        self.assertIsInstance(session.uid, bytes) 
Example #26
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_sessionCaching(self):
        """
        L{Request.getSession} creates the session object only once per request;
        if it is called twice it returns the identical result.
        """
        site = server.Site(resource.Resource())
        d = DummyChannel()
        request = server.Request(d, 1)
        request.site = site
        request.sitepath = []
        session1 = request.getSession()
        self.addCleanup(session1.expire)
        session2 = request.getSession()
        self.assertIs(session1, session2) 
Example #27
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_getSessionExistent(self):
        """
        L{site.getSession} gets a previously generated session, by its unique
        ID.
        """
        site = server.Site(resource.Resource())
        createdSession = self.getAutoExpiringSession(site)

        retrievedSession = site.getSession(createdSession.uid)

        self.assertIs(createdSession, retrievedSession) 
Example #28
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_getSessionNonExistent(self):
        """
        L{site.getSession} raises a L{KeyError} if the session is not found.
        """
        site = server.Site(resource.Resource())

        self.assertRaises(KeyError, site.getSession, b'no-such-uid') 
Example #29
Source File: test_webclient.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.agent = None # for twisted.web.client.Agent test
        self.cleanupServerConnections = 0
        r = resource.Resource()
        r.putChild(b"file", Data(b"0123456789", "text/html"))
        r.putChild(b"redirect", Redirect(b"/file"))
        self.infiniteRedirectResource = CountingRedirect(b"/infiniteRedirect")
        r.putChild(b"infiniteRedirect", self.infiniteRedirectResource)
        r.putChild(b"wait", ForeverTakingResource())
        r.putChild(b"write-then-wait", ForeverTakingResource(write=True))
        r.putChild(b"never-read", ForeverTakingNoReadingResource())
        r.putChild(b"error", ErrorResource())
        r.putChild(b"nolength", NoLengthResource())
        r.putChild(b"host", HostHeaderResource())
        r.putChild(b"payload", PayloadResource())
        r.putChild(b"broken", BrokenDownloadResource())
        r.putChild(b"cookiemirror", CookieMirrorResource())
        r.putChild(b'delay1', DelayResource(1))
        r.putChild(b'delay2', DelayResource(2))

        self.afterFoundGetCounter = CountingResource()
        r.putChild(b"afterFoundGetCounter", self.afterFoundGetCounter)
        r.putChild(b"afterFoundGetRedirect", Redirect(b"/afterFoundGetCounter"))

        miscasedHead = Data(b"miscased-head GET response content", "major/minor")
        miscasedHead.render_Head = lambda request: b"miscased-head content"
        r.putChild(b"miscased-head", miscasedHead)

        self.extendedRedirect = ExtendedRedirect(b'/extendedRedirect')
        r.putChild(b"extendedRedirect", self.extendedRedirect)
        self.site = server.Site(r, timeout=None)
        self.wrapper = WrappingFactory(self.site)
        self.port = self._listen(self.wrapper)
        self.portno = self.port.getHost().port 
Example #30
Source File: test_web.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_defaultReactor(self):
        """
        If not value is passed to L{server.Session.__init__}, the global
        reactor is used.
        """
        session = server.Session(server.Site(resource.Resource()), b'123')
        self.assertIdentical(session._reactor, reactor)