Python twisted.web.resource.IResource() Examples
The following are 30
code examples of twisted.web.resource.IResource().
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: wrapper.py From python-for-android with Apache License 2.0 | 6 votes |
def _authorizedResource(self, request): """ Get the L{IResource} which the given request is authorized to receive. If the proper authorization headers are present, the resource will be requested from the portal. If not, an anonymous login attempt will be made. """ authheader = request.getHeader('authorization') if not authheader: return util.DeferredResource(self._login(Anonymous())) factory, respString = self._selectParseHeader(authheader) if factory is None: return UnauthorizedResource(self._credentialFactories) try: credentials = factory.decode(respString, request) except error.LoginFailed: return UnauthorizedResource(self._credentialFactories) except: log.err(None, "Unexpected failure from credentials factory") return ErrorPage(500, None, None) else: return util.DeferredResource(self._login(credentials))
Example #2
Source File: wrapper.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def _authorizedResource(self, request): """ Get the L{IResource} which the given request is authorized to receive. If the proper authorization headers are present, the resource will be requested from the portal. If not, an anonymous login attempt will be made. """ authheader = request.getHeader(b'authorization') if not authheader: return util.DeferredResource(self._login(Anonymous())) factory, respString = self._selectParseHeader(authheader) if factory is None: return UnauthorizedResource(self._credentialFactories) try: credentials = factory.decode(respString, request) except error.LoginFailed: return UnauthorizedResource(self._credentialFactories) except: log.err(None, "Unexpected failure from credentials factory") return ErrorPage(500, None, None) else: return util.DeferredResource(self._login(credentials))
Example #3
Source File: test_httpauth.py From learn_python3_spider with MIT License | 6 votes |
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 #4
Source File: test_httpauth.py From learn_python3_spider with MIT License | 6 votes |
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 #5
Source File: test_httpauth.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
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 #6
Source File: auth.py From pixelated-user-agent with GNU Affero General Public License v3.0 | 6 votes |
def _login(self, credentials, request): pattern = re.compile("^/sandbox/") def loginSucceeded(args): interface, avatar, logout = args if avatar == checkers.ANONYMOUS and not pattern.match(request.path): return self._anonymous_resource else: return self._root_resource def loginFailed(result): if result.check(error.Unauthorized, error.LoginFailed): return UnauthorizedResource(self._credentialFactories) else: log.err( result, "HTTPAuthSessionWrapper.getChildWithDefault encountered " "unexpected error") return ErrorPage(500, None, None) d = self._portal.login(credentials, None, IResource) d.addCallbacks(loginSucceeded, loginFailed) return d
Example #7
Source File: test_httpauth.py From python-for-android with Apache License 2.0 | 6 votes |
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.assertEquals(request.written, [self.childContent]) d.addCallback(cbFinished) request.render(child) return d
Example #8
Source File: test_httpauth.py From python-for-android with Apache License 2.0 | 6 votes |
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.assertEquals(request.written, [self.avatarContent]) d.addCallback(cbFinished) request.render(child) return d
Example #9
Source File: wrapper.py From learn_python3_spider with MIT License | 6 votes |
def _authorizedResource(self, request): """ Get the L{IResource} which the given request is authorized to receive. If the proper authorization headers are present, the resource will be requested from the portal. If not, an anonymous login attempt will be made. """ authheader = request.getHeader(b'authorization') if not authheader: return util.DeferredResource(self._login(Anonymous())) factory, respString = self._selectParseHeader(authheader) if factory is None: return UnauthorizedResource(self._credentialFactories) try: credentials = factory.decode(respString, request) except error.LoginFailed: return UnauthorizedResource(self._credentialFactories) except: self._log.failure("Unexpected failure from credentials factory") return ErrorPage(500, None, None) else: return util.DeferredResource(self._login(credentials))
Example #10
Source File: test_wsgi.py From python-for-android with Apache License 2.0 | 5 votes |
def test_unsupported(self): """ A L{WSGIResource} cannot have L{IResource} children. Its C{getChildWithDefault} and C{putChild} methods raise L{RuntimeError}. """ self.assertRaises( RuntimeError, self.resource.getChildWithDefault, "foo", Request(DummyChannel(), False)) self.assertRaises( RuntimeError, self.resource.putChild, "foo", Resource())
Example #11
Source File: wsgi.py From python-for-android with Apache License 2.0 | 5 votes |
def putChild(self, path, child): """ Reject attempts to add a child resource to this resource. The WSGI application object handles all path segments beneath this resource, so L{IResource} children can never be found. """ raise RuntimeError("Cannot put IResource children under WSGIResource")
Example #12
Source File: wrapper.py From python-for-android with Apache License 2.0 | 5 votes |
def render(self, request): """ Find the L{IResource} avatar suitable for the given request, if possible, and render it. Otherwise, perhaps render an error page requiring authorization or describing an internal server failure. """ return self._authorizedResource(request).render(request)
Example #13
Source File: wrapper.py From python-for-android with Apache License 2.0 | 5 votes |
def _login(self, credentials): """ Get the L{IResource} avatar for the given credentials. @return: A L{Deferred} which will be called back with an L{IResource} avatar or which will errback if authentication fails. """ d = self._portal.login(credentials, None, IResource) d.addCallbacks(self._loginSucceeded, self._loginFailed) return d
Example #14
Source File: test_distrib.py From python-for-android with Apache License 2.0 | 5 votes |
def test_interface(self): """ L{UserDirectory} instances provide L{resource.IResource}. """ self.assertTrue(verifyObject(resource.IResource, self.directory))
Example #15
Source File: test_httpauth.py From python-for-android with Apache License 2.0 | 5 votes |
def requestAvatar(self, avatarId, mind, *interfaces): if IResource in interfaces: self.loggedIn += 1 return IResource, self.avatarFactory(avatarId), self.logout raise NotImplementedError()
Example #16
Source File: test_httpauth.py From python-for-android with Apache License 2.0 | 5 votes |
def _authorizedBasicLogin(self, request): """ Add an I{basic authorization} header to the given request and then dispatch it, starting from C{self.wrapper} and returning the resulting L{IResource}. """ authorization = b64encode(self.username + ':' + self.password) request.headers['authorization'] = 'Basic ' + authorization return getChildForRequest(self.wrapper, request)
Example #17
Source File: agent.py From ccs-calendarserver with Apache License 2.0 | 5 votes |
def requestAvatar(self, avatarId, mind, *interfaces): if IResource in interfaces: if avatarId.shortNames[0] in self.allowedAvatarIds: return (IResource, self.root, lambda: None) else: return (IResource, ForbiddenResource(), lambda: None) raise NotImplementedError()
Example #18
Source File: auth.py From pixelated-user-agent with GNU Affero General Public License v3.0 | 5 votes |
def requestAvatar(self, avatarId, mind, *interfaces): if IResource in interfaces: return IResource, avatarId, lambda: None raise NotImplementedError()
Example #19
Source File: view.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def registerViewForModel(view, model): """ Registers `view' as an adapter of `model' for L{interfaces.IView}. """ components.registerAdapter(view, model, interfaces.IView) # adapter = resource.IResource(model, None) # if adapter is None and resource.IResource.providedBy(view): # components.registerAdapter(view, model, resource.IResource) #sibling imports:: # If no widget/handler was found in the container controller or view, these # modules will be searched.
Example #20
Source File: tapestry.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def getChild(self, path, request): if path == '': path = 'index' path = path.replace(".","_") cm = getattr(self, "wchild_"+path, None) if cm: p = cm(request) if isinstance(p, Deferred): return util.DeferredResource(p) adapter = IResource(p, None) if adapter is not None: return adapter # maybe we want direct support for ModelLoader? # cl = getattr(self, "wload_"+path, None) #??? return Resource.getChild(self, path, request)
Example #21
Source File: simpleguard.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def requestAvatar(self, avatarId, mind, *interfaces): if resource.IResource not in interfaces: raise NotImplementedError("no interface") if avatarId: return (resource.IResource, MarkAuthenticatedResource(self.resource, avatarId), lambda:None) else: return resource.IResource, self.nonauthenticated, lambda:None
Example #22
Source File: guard.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def __init__(self, portal, callback=None, errback=None): """Constructs a UsernamePasswordWrapper around the given portal. @param portal: A cred portal for your web application. The checkers associated with this portal must be able to accept username/password credentials. @type portal: L{twisted.cred.portal.Portal} @param callback: Gets called after a successful login attempt. A resource that redirects to "." will display the avatar resource. If this parameter isn't provided, defaults to a standard Woven "Thank You" page. @type callback: A callable that accepts a Woven L{model<twisted.web.woven.interfaces.IModel>} and returns a L{IResource<twisted.web.resource.Resource>}. @param errback: Gets called after a failed login attempt. If this parameter is not provided, defaults to a the standard Woven form error (i.e. The original form on a page of its own, with errors noted.) @type errback: A callable that accepts a Woven L{model<twisted.web.woven.interfaces.IModel>} and returns a L{IResource<twisted.web.resource.Resource>}. """ Resource.__init__(self) self.portal = portal self.callback = callback self.errback = errback
Example #23
Source File: static.py From BitTorrent with GNU General Public License v3.0 | 5 votes |
def getChild(self, path, request): """See twisted.web.Resource.getChild. """ self.restat() if not self.isdir(): return self.childNotFound if path: fpath = self.child(path) else: fpath = self.childSearchPreauth(*self.indexNames) if fpath is None: return self.directoryListing() if not fpath.exists(): fpath = fpath.siblingExtensionSearch(*self.ignoredExts) if fpath is None: return self.childNotFound if platformType == "win32": # don't want .RPY to be different than .rpy, since that would allow # source disclosure. processor = InsensitiveDict(self.processors).get(fpath.splitext()[1]) else: processor = self.processors.get(fpath.splitext()[1]) if processor: return resource.IResource(processor(fpath.path, self.registry)) return self.createSimilarFile(fpath.path) # methods to allow subclasses to e.g. decrypt files on the fly:
Example #24
Source File: test_websockets.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def test_IResource(self): """ L{WebSocketsResource} implements L{IResource}. """ self.assertTrue(verifyObject(IResource, self.resource))
Example #25
Source File: websockets.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def getChildWithDefault(self, name, request): """ Reject attempts to retrieve a child resource. All path segments beyond the one which refers to this resource are handled by the WebSocket connection. @type name: C{bytes} @param name: A single path component from a requested URL. @type request: L{twisted.web.iweb.IRequest} provider @param request: The request received. """ raise RuntimeError( "Cannot get IResource children from WebSocketsResource" )
Example #26
Source File: websockets.py From maas with GNU Affero General Public License v3.0 | 5 votes |
def putChild(self, path, child): """ Reject attempts to add a child resource to this resource. The WebSocket connection handles all path segments beneath this resource, so L{IResource} children can never be found. @type path: C{bytes} @param path: A single path component. @type child: L{IResource} provider @param child: A resource to put underneat this one. """ raise RuntimeError( "Cannot put IResource children under WebSocketsResource" )
Example #27
Source File: test_wsgi.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def test_unsupported(self): """ A L{WSGIResource} cannot have L{IResource} children. Its C{getChildWithDefault} and C{putChild} methods raise L{RuntimeError}. """ self.assertRaises( RuntimeError, self.resource.getChildWithDefault, b"foo", Request(DummyChannel(), False)) self.assertRaises( RuntimeError, self.resource.putChild, b"foo", Resource())
Example #28
Source File: wsgi.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def getChildWithDefault(self, name, request): """ Reject attempts to retrieve a child resource. All path segments beyond the one which refers to this resource are handled by the WSGI application object. """ raise RuntimeError("Cannot get IResource children from WSGIResource")
Example #29
Source File: wsgi.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def putChild(self, path, child): """ Reject attempts to add a child resource to this resource. The WSGI application object handles all path segments beneath this resource, so L{IResource} children can never be found. """ raise RuntimeError("Cannot put IResource children under WSGIResource")
Example #30
Source File: wrapper.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 5 votes |
def render(self, request): """ Find the L{IResource} avatar suitable for the given request, if possible, and render it. Otherwise, perhaps render an error page requiring authorization or describing an internal server failure. """ return self._authorizedResource(request).render(request)