本文整理汇总了Python中twisted.web.resource.Resource方法的典型用法代码示例。如果您正苦于以下问题:Python resource.Resource方法的具体用法?Python resource.Resource怎么用?Python resource.Resource使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.web.resource
的用法示例。
在下文中一共展示了resource.Resource方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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)
示例2: ResourceScript
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例3: test_render
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例4: testDistrib
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例5: test_requestHeaders
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例6: test_requestResponseCode
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例7: test_requestResponseCodeMessage
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例8: test_getChildWithDefaultAuthorized
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例9: test_renderAuthorized
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例10: test_anonymousAccess
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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
示例11: test_sessionUIDGeneration
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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)
示例12: test_processingFailedNoTraceback
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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()))
示例13: test_processingFailedDisplayTraceback
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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()))
示例14: test_processingFailedDisplayTracebackHandlesUnicode
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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()))
示例15: test_sessionDifferentFromSecureSession
# 需要导入模块: from twisted.web import resource [as 别名]
# 或者: from twisted.web.resource import Resource [as 别名]
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)