本文整理匯總了Python中twisted.web.http方法的典型用法代碼示例。如果您正苦於以下問題:Python web.http方法的具體用法?Python web.http怎麽用?Python web.http使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類twisted.web
的用法示例。
在下文中一共展示了web.http方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_wsgiURLScheme
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def test_wsgiURLScheme(self):
"""
The C{'wsgi.url_scheme'} key of the C{environ} C{dict} passed to the
application has the request URL scheme.
"""
# XXX Does this need to be different if the request is for an absolute
# URL?
def channelFactory():
channel = DummyChannel()
channel.transport = DummyChannel.SSL()
return channel
self.channelFactory = DummyChannel
httpDeferred = self.render('GET', '1.1', [], [''])
httpDeferred.addCallback(self.environKeyEqual('wsgi.url_scheme', 'http'))
self.channelFactory = channelFactory
httpsDeferred = self.render('GET', '1.1', [], [''])
httpsDeferred.addCallback(self.environKeyEqual('wsgi.url_scheme', 'https'))
return gatherResults([httpDeferred, httpsDeferred])
示例2: test_no_immediate_authentication
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def test_no_immediate_authentication(self):
"""
``cinder_from_configuration`` returns an API object even if it can't
connect to the keystone server endpoint.
Keystone authentication is postponed until the API is first used.
"""
backend, api_args = backend_and_api_args_from_configuration({
"backend": "openstack",
"auth_plugin": "password",
"region": "RegionOne",
"username": "non-existent-user",
"password": "non-working-password",
"auth_url": "http://127.0.0.2:5000/v2.0",
})
# This will fail if loading the API depends on being able to connect to
# the auth_url (above)
get_api(
backend=backend,
api_args=api_args,
reactor=object(),
cluster_id=make_cluster_id(TestTypes.FUNCTIONAL),
)
示例3: setUp
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def setUp(self):
super(ComputeInstanceIDTests, self).setUp()
backend, api_args = backend_and_api_args_from_configuration({
"backend": "openstack",
"auth_plugin": "rackspace",
"region": "ORD",
"username": "unknown_user",
"api_key": "unknown_api_key",
"auth_url": "http://{}:{}/identity/v2.0".format(*find_free_port()),
})
self.api = get_api(
backend=backend,
api_args=api_args,
reactor=object(),
cluster_id=make_cluster_id(TestTypes.FUNCTIONAL),
)
示例4: open_in_browser
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def open_in_browser(response, _openfunc=webbrowser.open):
"""Open the given response in a local web browser, populating the <base>
tag for external links to work
"""
from scrapy.http import HtmlResponse, TextResponse
# XXX: this implementation is a bit dirty and could be improved
body = response.body
if isinstance(response, HtmlResponse):
if b'<base' not in body:
repl = '<head><base href="%s">' % response.url
body = body.replace(b'<head>', to_bytes(repl))
ext = '.html'
elif isinstance(response, TextResponse):
ext = '.txt'
else:
raise TypeError("Unsupported response type: %s" %
response.__class__.__name__)
fd, fname = tempfile.mkstemp(ext)
os.write(fd, body)
os.close(fd)
return _openfunc("file://%s" % fname)
示例5: test_wsgiErrors
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def test_wsgiErrors(self):
"""
The C{'wsgi.errors'} key of the C{environ} C{dict} passed to the
application is a file-like object (as defined in the U{Input and Errors
Streams<http://www.python.org/dev/peps/pep-0333/#input-and-error-streams>}
section of PEP 333) which converts bytes written to it into events for
the logging system.
"""
events = []
addObserver(events.append)
self.addCleanup(removeObserver, events.append)
errors = self.render('GET', '1.1', [], [''])
def cbErrors(result):
environ, startApplication = result
errors = environ['wsgi.errors']
errors.write('some message\n')
errors.writelines(['another\nmessage\n'])
errors.flush()
self.assertEqual(events[0]['message'], ('some message\n',))
self.assertEqual(events[0]['system'], 'wsgi')
self.assertTrue(events[0]['isError'])
self.assertEqual(events[1]['message'], ('another\nmessage\n',))
self.assertEqual(events[1]['system'], 'wsgi')
self.assertTrue(events[1]['isError'])
self.assertEqual(len(events), 2)
errors.addCallback(cbErrors)
return errors
示例6: _headersTest
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def _headersTest(self, appHeaders, expectedHeaders):
"""
Verify that if the response headers given by C{appHeaders} are passed
to the I{start_response} callable, then the response header lines given
by C{expectedHeaders} plus I{Server} and I{Date} header lines are
included in the response.
"""
# Make the Date header value deterministic
self.patch(http, 'datetimeToString', lambda: 'Tuesday')
channel = DummyChannel()
def applicationFactory():
def application(environ, startResponse):
startResponse('200 OK', appHeaders)
return iter(())
return application
d, requestFactory = self.requestFactoryFactory()
def cbRendered(ignored):
response = channel.transport.written.getvalue()
headers, rest = response.split(b'\r\n\r\n', 1)
headerLines = headers.split(b'\r\n')[1:]
headerLines.sort()
allExpectedHeaders = expectedHeaders + [
b'Date: Tuesday',
b'Server: ' + version,
b'Transfer-Encoding: chunked']
allExpectedHeaders.sort()
self.assertEqual(headerLines, allExpectedHeaders)
d.addCallback(cbRendered)
self.lowLevelRender(
requestFactory, applicationFactory,
lambda: channel, 'GET', '1.1', [], [''], None, [])
return d
示例7: get_meta_refresh
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def get_meta_refresh(response, ignore_tags=('script', 'noscript')):
"""Parse the http-equiv refrsh parameter from the given response"""
if response not in _metaref_cache:
text = response.text[0:4096]
_metaref_cache[response] = html.get_meta_refresh(text, response.url,
response.encoding, ignore_tags=ignore_tags)
return _metaref_cache[response]
示例8: response_status_message
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def response_status_message(status):
"""Return status code plus status text descriptive message
"""
message = http.RESPONSES.get(int(status), "Unknown Status")
return '%s %s' % (status, to_native_str(message))
示例9: response_httprepr
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def response_httprepr(response):
"""Return raw HTTP representation (as bytes) of the given response. This
is provided only for reference, since it's not the exact stream of bytes
that was received (that's not exposed by Twisted).
"""
s = b"HTTP/1.1 " + to_bytes(str(response.status)) + b" " + \
to_bytes(http.RESPONSES.get(response.status, b'')) + b"\r\n"
if response.headers:
s += response.headers.to_string() + b"\r\n"
s += b"\r\n"
s += response.body
return s
示例10: test_wsgiErrors
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def test_wsgiErrors(self):
"""
The C{'wsgi.errors'} key of the C{environ} C{dict} passed to the
application is a file-like object (as defined in the U{Input and Errors
Streams<http://www.python.org/dev/peps/pep-0333/#input-and-error-streams>}
section of PEP 333) which converts bytes written to it into events for
the logging system.
"""
events = []
addObserver(events.append)
self.addCleanup(removeObserver, events.append)
errors = self.render('GET', '1.1', [], [''])
def cbErrors((environ, startApplication)):
errors = environ['wsgi.errors']
errors.write('some message\n')
errors.writelines(['another\nmessage\n'])
errors.flush()
self.assertEqual(events[0]['message'], ('some message\n',))
self.assertEqual(events[0]['system'], 'wsgi')
self.assertTrue(events[0]['isError'])
self.assertEqual(events[1]['message'], ('another\nmessage\n',))
self.assertEqual(events[1]['system'], 'wsgi')
self.assertTrue(events[1]['isError'])
self.assertEqual(len(events), 2)
errors.addCallback(cbErrors)
return errors
示例11: _headersTest
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def _headersTest(self, appHeaders, expectedHeaders):
"""
Verify that if the response headers given by C{appHeaders} are passed
to the I{start_response} callable, then the response header lines given
by C{expectedHeaders} plus I{Server} and I{Date} header lines are
included in the response.
"""
# Make the Date header value deterministic
self.patch(http, 'datetimeToString', lambda: 'Tuesday')
channel = DummyChannel()
def applicationFactory():
def application(environ, startResponse):
startResponse('200 OK', appHeaders)
return iter(())
return application
d, requestFactory = self.requestFactoryFactory()
def cbRendered(ignored):
response = channel.transport.written.getvalue()
headers, rest = response.split('\r\n\r\n', 1)
headerLines = headers.split('\r\n')[1:]
headerLines.sort()
allExpectedHeaders = expectedHeaders + [
'Date: Tuesday',
'Server: ' + version,
'Transfer-Encoding: chunked']
allExpectedHeaders.sort()
self.assertEqual(headerLines, allExpectedHeaders)
d.addCallback(cbRendered)
request = self.lowLevelRender(
requestFactory, applicationFactory,
lambda: channel, 'GET', '1.1', [], [''], None, [])
return d
示例12: testSessionInit
# 需要導入模塊: from twisted import web [as 別名]
# 或者: from twisted.web import http [as 別名]
def testSessionInit(self):
sessWrapped = static.Data("you should never see this", "text/plain")
swChild = static.Data("NO", "text/plain")
sessWrapped.putChild("yyy",swChild)
swrap = guard.SessionWrapper(sessWrapped)
da = static.Data("b","text/plain")
da.putChild("xxx", swrap)
st = FakeSite(da)
chan = FakeHTTPChannel()
chan.site = st
# first we're going to make sure that the session doesn't get set by
# accident when browsing without first explicitly initializing the
# session
req = FakeHTTPRequest(chan, queued=0)
req.requestReceived("GET", "/xxx/yyy", "1.0")
assert len(req._cookieCache.values()) == 0, req._cookieCache.values()
self.assertEquals(req.getSession(),None)
# now we're going to make sure that the redirect and cookie are properly set
req = FakeHTTPRequest(chan, queued=0)
req.requestReceived("GET", "/xxx/"+guard.INIT_SESSION, "1.0")
ccv = req._cookieCache.values()
self.assertEquals(len(ccv),1)
cookie = ccv[0]
# redirect set?
self.failUnless(req.headers.has_key('location'))
# redirect matches cookie?
self.assertEquals(req.headers['location'].split('/')[-1], guard.SESSION_KEY+cookie)
# URL is correct?
self.assertEquals(req.headers['location'],
'http://fake.com/xxx/'+guard.SESSION_KEY+cookie)
oldreq = req
# now let's try with a request for the session-cookie URL that has a cookie set
url = "/"+(oldreq.headers['location'].split('http://fake.com/',1))[1]
req = chan.makeFakeRequest(url)
self.assertEquals(req.headers['location'].split('?')[0],
'http://fake.com/xxx/')
for sz in swrap.sessions.values():
sz.expire()