Python twisted.web.resource.NoResource() Examples

The following are 30 code examples of twisted.web.resource.NoResource(). 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: script.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def render(self, request):
        """Render me to a web client.

        Load my file, execute it in a special namespace (with 'request' and
        '__file__' global vars) and finish the request.  Output to the web-page
        will NOT be handled with print - standard output goes to the log - but
        with request.write.
        """
        request.setHeader("x-powered-by","Twisted/%s" % copyright.version)
        namespace = {'request': request,
                     '__file__': self.filename,
                     'registry': self.registry}
        try:
            execfile(self.filename, namespace, namespace)
        except IOError, e:
            if e.errno == 2: #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(resource.NoResource("File not found.").render(request)) 
Example #2
Source File: test_vhost.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_getChild(self):
        """
        L{_HostResource.getChild} returns the proper I{Resource} for the vhost
        embedded in the URL.  Verify that returning the proper I{Resource}
        required changing the I{Host} in the header.
        """
        bazroot = Data(b'root data', "")
        bazuri  = Data(b'uri data', "")
        baztest = Data(b'test data', "")
        bazuri.putChild(b'test', baztest)
        bazroot.putChild(b'uri', bazuri)
        hr = _HostResource()

        root = NameVirtualHost()
        root.default = Data(b'default data', "")
        root.addHost(b'baz.com', bazroot)

        request = DummyRequest([b'uri', b'test'])
        request.prepath = [b'bar', b'http', b'baz.com']
        request.site = Site(root)
        request.isSecure = lambda: False
        request.host = b''

        step = hr.getChild(b'baz.com', request) # Consumes rest of path
        self.assertIsInstance(step, Data)

        request = DummyRequest([b'uri', b'test'])
        step = root.getChild(b'uri', request)
        self.assertIsInstance(step, NoResource) 
Example #3
Source File: test_webapp.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_getResourceFor_returns_no_resource_wo_underlay(self):
        root = Resource()
        site = OverlaySite(root)
        request = DummyRequest([b"MAAS"])
        resource = site.getResourceFor(request)
        self.assertThat(resource, IsInstance(NoResource)) 
Example #4
Source File: root_resource.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def get(self, path):
        return self._registry.get(path) or NoResource() 
Example #5
Source File: login_resource.py    From pixelated-user-agent with GNU Affero General Public License v3.0 5 votes vote down vote up
def getChild(self, path, request):
        if path == '':
            return self
        if path == 'login':
            return self
        if path == 'status':
            return LoginStatusResource(self._services_factory)
        if path == AccountRecoveryResource.BASE_URL:
            return AccountRecoveryResource(self._services_factory)
        if not self.is_logged_in(request):
            return UnAuthorizedResource()
        return NoResource() 
Example #6
Source File: test_resource.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_noResourceRendering(self):
        """
        Like L{ErrorPageTests.test_noResourceRendering}, but flush the
        deprecation warning emitted by instantiating L{error.NoResource}.
        """
        ErrorPageTests.test_noResourceRendering(self)
        self._assertWarning('NoResource', self.noResource) 
Example #7
Source File: test_resource.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def noResource(self, *args):
        return error.NoResource(*args) 
Example #8
Source File: test_resource.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_noResourceRendering(self):
        """
        L{NoResource} sets the HTTP I{NOT FOUND} code.
        """
        detail = "long message"
        page = self.noResource(detail)
        self._pageRenderingTest(page, NOT_FOUND, "No Such Resource", detail) 
Example #9
Source File: twcgi.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def render(self, request):
        notFound = resource.NoResource(
            "CGI directories do not support directory listing.")
        return notFound.render(request) 
Example #10
Source File: twcgi.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getChild(self, path, request):
        fnp = self.child(path)
        if not fnp.exists():
            return static.File.childNotFound
        elif fnp.isdir():
            return CGIDirectory(fnp.path)
        else:
            return CGIScript(fnp.path)
        return resource.NoResource() 
Example #11
Source File: error.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        warnings.warn(
            "twisted.web.error.NoResource is deprecated since Twisted 9.0.  "
            "See twisted.web.resource.NoResource.", DeprecationWarning,
            stacklevel=2)
        _resource.NoResource.__init__(self, *args, **kwargs) 
Example #12
Source File: distrib.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getChild(self, name, request):
        if name == '':
            return self

        td = '.twistd'

        if name[-len(td):] == td:
            username = name[:-len(td)]
            sub = 1
        else:
            username = name
            sub = 0
        try:
            pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
                     = self._pwd.getpwnam(username)
        except KeyError:
            return resource.NoResource()
        if sub:
            twistdsock = os.path.join(pw_dir, self.userSocketName)
            rs = ResourceSubscription('unix',twistdsock)
            self.putChild(name, rs)
            return rs
        else:
            path = os.path.join(pw_dir, self.userDirName)
            if not os.path.exists(path):
                return resource.NoResource()
            return static.File(path) 
Example #13
Source File: script.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def render(self, request):
        return resource.NoResource().render(request) 
Example #14
Source File: script.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def getChild(self, path, request):
        fn = os.path.join(self.path, path)

        if os.path.isdir(fn):
            return ResourceScriptDirectory(fn, self.registry)
        if os.path.exists(fn):
            return ResourceScript(fn, self.registry)
        return resource.NoResource() 
Example #15
Source File: test_vhost.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_getChild(self):
        """
        L{NameVirtualHost.getChild} returns correct I{Resource} based off
        the header and modifies I{Request} to ensure proper prepath and
        postpath are set.
        """
        virtualHostResource = NameVirtualHost()
        leafResource = Data(b"leaf data", "")
        leafResource.isLeaf = True
        normResource = Data(b"norm data", "")
        virtualHostResource.addHost(b'leaf.example.org', leafResource)
        virtualHostResource.addHost(b'norm.example.org', normResource)

        request = DummyRequest([])
        request.requestHeaders.addRawHeader(b'host', b'norm.example.org')
        request.prepath = [b'']

        self.assertIsInstance(virtualHostResource.getChild(b'', request),
                              NoResource)
        self.assertEqual(request.prepath, [b''])
        self.assertEqual(request.postpath, [])

        request = DummyRequest([])
        request.requestHeaders.addRawHeader(b'host', b'leaf.example.org')
        request.prepath = [b'']

        self.assertIsInstance(virtualHostResource.getChild(b'', request),
                              Data)
        self.assertEqual(request.prepath,  [])
        self.assertEqual(request.postpath, [b'']) 
Example #16
Source File: script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def getChild(self, path, request):
        fn = os.path.join(self.path, path)

        if os.path.isdir(fn):
            return ResourceScriptDirectory(fn, self.registry)
        if os.path.exists(fn):
            return ResourceScript(fn, self.registry)
        return resource.NoResource() 
Example #17
Source File: twcgi.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def render(self, request):
        notFound = resource.NoResource(
            "CGI directories do not support directory listing.")
        return notFound.render(request) 
Example #18
Source File: vhost.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _getResourceForRequest(self, request):
        """(Internal) Get the appropriate resource for the given host.
        """
        hostHeader = request.getHeader(b'host')
        if hostHeader == None:
            return self.default or resource.NoResource()
        else:
            host = hostHeader.lower().split(b':', 1)[0]
        return (self.hosts.get(host, self.default)
                or resource.NoResource("host %s not in vhost map" % repr(host))) 
Example #19
Source File: distrib.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def getChild(self, name, request):
        if name == '':
            return self

        td = '.twistd'

        if name[-len(td):] == td:
            username = name[:-len(td)]
            sub = 1
        else:
            username = name
            sub = 0
        try:
            pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
                     = self._pwd.getpwnam(username)
        except KeyError:
            return resource.NoResource()
        if sub:
            twistdsock = os.path.join(pw_dir, self.userSocketName)
            rs = ResourceSubscription('unix',twistdsock)
            self.putChild(name, rs)
            return rs
        else:
            path = os.path.join(pw_dir, self.userDirName)
            if not os.path.exists(path):
                return resource.NoResource()
            return static.File(path) 
Example #20
Source File: script.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def render(self, request):
        """
        Render me to a web client.

        Load my file, execute it in a special namespace (with 'request' and
        '__file__' global vars) and finish the request.  Output to the web-page
        will NOT be handled with print - standard output goes to the log - but
        with request.write.
        """
        request.setHeader(b"x-powered-by", networkString("Twisted/%s" % copyright.version))
        namespace = {'request': request,
                     '__file__': _coerceToFilesystemEncoding("", self.filename),
                     'registry': self.registry}
        try:
            execfile(self.filename, namespace, namespace)
        except IOError as e:
            if e.errno == 2: #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(resource.NoResource("File not found.").render(request))
        except:
            io = NativeStringIO()
            traceback.print_exc(file=io)
            output = util._PRE(io.getvalue())
            if _PY3:
                output = output.encode("utf8")
            request.write(output)
        request.finish()
        return server.NOT_DONE_YET 
Example #21
Source File: script.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def render(self, request):
        return resource.NoResource().render(request) 
Example #22
Source File: script.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def getChild(self, path, request):
        fn = os.path.join(self.path, path)

        if os.path.isdir(fn):
            return ResourceScriptDirectory(fn, self.registry)
        if os.path.exists(fn):
            return ResourceScript(fn, self.registry)
        return resource.NoResource() 
Example #23
Source File: test_vhost.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_getChild(self):
        """
        L{NameVirtualHost.getChild} returns correct I{Resource} based off
        the header and modifies I{Request} to ensure proper prepath and
        postpath are set.
        """
        virtualHostResource = NameVirtualHost()
        leafResource = Data(b"leaf data", "")
        leafResource.isLeaf = True
        normResource = Data(b"norm data", "")
        virtualHostResource.addHost(b'leaf.example.org', leafResource)
        virtualHostResource.addHost(b'norm.example.org', normResource)

        request = DummyRequest([])
        request.requestHeaders.addRawHeader(b'host', b'norm.example.org')
        request.prepath = [b'']

        self.assertIsInstance(virtualHostResource.getChild(b'', request),
                              NoResource)
        self.assertEqual(request.prepath, [b''])
        self.assertEqual(request.postpath, [])

        request = DummyRequest([])
        request.requestHeaders.addRawHeader(b'host', b'leaf.example.org')
        request.prepath = [b'']

        self.assertIsInstance(virtualHostResource.getChild(b'', request),
                              Data)
        self.assertEqual(request.prepath,  [])
        self.assertEqual(request.postpath, [b'']) 
Example #24
Source File: test_vhost.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_getChild(self):
        """
        L{_HostResource.getChild} returns the proper I{Resource} for the vhost
        embedded in the URL.  Verify that returning the proper I{Resource}
        required changing the I{Host} in the header.
        """
        bazroot = Data(b'root data', "")
        bazuri  = Data(b'uri data', "")
        baztest = Data(b'test data', "")
        bazuri.putChild(b'test', baztest)
        bazroot.putChild(b'uri', bazuri)
        hr = _HostResource()

        root = NameVirtualHost()
        root.default = Data(b'default data', "")
        root.addHost(b'baz.com', bazroot)

        request = DummyRequest([b'uri', b'test'])
        request.prepath = [b'bar', b'http', b'baz.com']
        request.site = Site(root)
        request.isSecure = lambda: False
        request.host = b''

        step = hr.getChild(b'baz.com', request) # Consumes rest of path
        self.assertIsInstance(step, Data)

        request = DummyRequest([b'uri', b'test'])
        step = root.getChild(b'uri', request)
        self.assertIsInstance(step, NoResource) 
Example #25
Source File: twcgi.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def render(self, request):
        notFound = resource.NoResource(
            "CGI directories do not support directory listing.")
        return notFound.render(request) 
Example #26
Source File: vhost.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _getResourceForRequest(self, request):
        """(Internal) Get the appropriate resource for the given host.
        """
        hostHeader = request.getHeader(b'host')
        if hostHeader == None:
            return self.default or resource.NoResource()
        else:
            host = hostHeader.lower().split(b':', 1)[0]
        return (self.hosts.get(host, self.default)
                or resource.NoResource("host %s not in vhost map" % repr(host))) 
Example #27
Source File: distrib.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def getChild(self, name, request):
        if name == '':
            return self

        td = '.twistd'

        if name[-len(td):] == td:
            username = name[:-len(td)]
            sub = 1
        else:
            username = name
            sub = 0
        try:
            pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell \
                     = self._pwd.getpwnam(username)
        except KeyError:
            return resource.NoResource()
        if sub:
            twistdsock = os.path.join(pw_dir, self.userSocketName)
            rs = ResourceSubscription('unix',twistdsock)
            self.putChild(name, rs)
            return rs
        else:
            path = os.path.join(pw_dir, self.userDirName)
            if not os.path.exists(path):
                return resource.NoResource()
            return static.File(path) 
Example #28
Source File: script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def render(self, request):
        """
        Render me to a web client.

        Load my file, execute it in a special namespace (with 'request' and
        '__file__' global vars) and finish the request.  Output to the web-page
        will NOT be handled with print - standard output goes to the log - but
        with request.write.
        """
        request.setHeader(b"x-powered-by", networkString("Twisted/%s" % copyright.version))
        namespace = {'request': request,
                     '__file__': _coerceToFilesystemEncoding("", self.filename),
                     'registry': self.registry}
        try:
            execfile(self.filename, namespace, namespace)
        except IOError as e:
            if e.errno == 2: #file not found
                request.setResponseCode(http.NOT_FOUND)
                request.write(resource.NoResource("File not found.").render(request))
        except:
            io = NativeStringIO()
            traceback.print_exc(file=io)
            output = util._PRE(io.getvalue())
            if _PY3:
                output = output.encode("utf8")
            request.write(output)
        request.finish()
        return server.NOT_DONE_YET 
Example #29
Source File: script.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def render(self, request):
        return resource.NoResource().render(request) 
Example #30
Source File: restapi.py    From OpenBazaar-Server with MIT License 4 votes vote down vote up
def get_image(self, request):
        @defer.inlineCallbacks
        def _showImage(resp=None):
            @defer.inlineCallbacks
            def _setContentDispositionAndSend(file_path, extension, content_type):
                request.setHeader('content-disposition', 'filename="%s.%s"' % (file_path, extension))
                request.setHeader('content-type', content_type)
                request.setHeader('cache-control', 'max-age=604800')

                f = open(file_path, "rb")
                yield FileSender().beginFileTransfer(f, request)
                f.close()
                defer.returnValue(0)

            if os.path.exists(image_path):
                yield _setContentDispositionAndSend(image_path, "jpg", "image/jpeg")
            else:
                request.setResponseCode(http.NOT_FOUND)
                request.write("No such image '%s'" % request.path)
            request.finish()

        if "hash" in request.args and len(request.args["hash"][0]) == 40:
            if self.db.filemap.get_file(request.args["hash"][0]) is not None:
                image_path = self.db.filemap.get_file(request.args["hash"][0])
            else:
                image_path = os.path.join(DATA_FOLDER, "cache", request.args["hash"][0])
            if not os.path.exists(image_path) and "guid" in request.args:
                node = None
                for connection in self.protocol.values():
                    if connection.handler.node is not None and \
                                    connection.handler.node.id == unhexlify(request.args["guid"][0]):
                        node = connection.handler.node
                        self.mserver.get_image(node, unhexlify(request.args["hash"][0])).addCallback(_showImage)
                if node is None:
                    _showImage()
            else:
                _showImage()
        else:
            request.write(NoResource().render(request))
            request.finish()

        return server.NOT_DONE_YET