本文整理汇总了Python中twisted.web.server.Request类的典型用法代码示例。如果您正苦于以下问题:Python Request类的具体用法?Python Request怎么用?Python Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Request类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: requestReceived
def requestReceived(self, command, path, version):
"""Processes the self"""
CORE.info('Receiving request...')
try:
# prevent twisted's processing by lowercasing method
Request.requestReceived(self, command.lower(), path, version)
finally:
self.method = command
# fix twisted's query string processing
self.__fix_twisted_query_string()
self.site = self.channel.site
self._set_default_response_headers()
try:
CORE.info('Parse request body...')
self._parse_request_payload()
except ValueError as err:
self.respond(bytes(err))
return
self._set_default_request_headers()
CORE.info('Authenticate? ...')
self._authenticate_and_process()
示例2: __init__
def __init__(self, counter, method, path, headers, content):
channel = HTTPChannel()
host = IPv4Address(b"TCP", b"127.0.0.1", 80)
channel.makeConnection(StringTransport(hostAddress=host))
Request.__init__(self, channel, False)
# An extra attribute for identifying this fake request
self._counter = counter
# Attributes a Request is supposed to have but we have to set ourselves
# because the base class mixes together too much other logic with the
# code that sets them.
self.prepath = []
self.requestHeaders = headers
self.content = BytesIO(content)
self.requestReceived(method, path, b"HTTP/1.1")
# requestReceived initializes the path attribute for us (but not
# postpath).
self.postpath = list(map(unquote, self.path[1:].split(b'/')))
# Our own notifyFinish / finish state because the inherited
# implementation wants to write confusing stuff to the transport when
# the request gets finished.
self._finished = False
self._finishedChannel = EventChannel()
# Our own state for the response body so we don't have to dig it out of
# the transport.
self._responseBody = b""
示例3: render
def render(self, resrc):
# this is called once a Resource has been found to serve the request; in our
# case the Resource in question will normally be a JsonResource.
# create a LogContext for this request
request_id = self.get_request_id()
logcontext = self.logcontext = LoggingContext(request_id)
logcontext.request = request_id
# override the Server header which is set by twisted
self.setHeader("Server", self.site.server_version_string)
with PreserveLoggingContext(self.logcontext):
# we start the request metrics timer here with an initial stab
# at the servlet name. For most requests that name will be
# JsonResource (or a subclass), and JsonResource._async_render
# will update it once it picks a servlet.
servlet_name = resrc.__class__.__name__
self._started_processing(servlet_name)
Request.render(self, resrc)
# record the arrival of the request *after*
# dispatching to the handler, so that the handler
# can update the servlet name in the request
# metrics
requests_counter.labels(self.get_method(),
self.request_metrics.name).inc()
示例4: test_renderRealRequest
def test_renderRealRequest(self):
"""
The request managed by L{WebSocketsResource.render} doesn't contain
unnecessary HTTP headers like I{Content-Type} or I{Transfer-Encoding}.
"""
channel = DummyChannel()
channel.transport = StringTransportWithDisconnection()
channel.transport.protocol = channel
request = Request(channel, False)
headers = {
"upgrade": "Websocket",
"connection": "Upgrade",
"sec-websocket-key": "secure",
"sec-websocket-version": "13"}
for key, value in headers.items():
request.requestHeaders.setRawHeaders(key, [value])
request.method = "GET"
request.clientproto = "HTTP/1.1"
result = self.resource.render(request)
self.assertEqual(NOT_DONE_YET, result)
self.assertEqual(
[("Connection", ["Upgrade"]),
("Upgrade", ["WebSocket"]),
("Sec-Websocket-Accept", ["oYBv54i42V5dw6KnZqOFroecUTc="])],
list(request.responseHeaders.getAllRawHeaders()))
self.assertEqual(
"HTTP/1.1 101 Switching Protocols\r\n"
"Connection: Upgrade\r\n"
"Upgrade: WebSocket\r\n"
"Sec-Websocket-Accept: oYBv54i42V5dw6KnZqOFroecUTc=\r\n\r\n",
channel.transport.value())
self.assertEqual(101, request.code)
self.assertIdentical(None, request.transport)
示例5: test_redirectToUnicodeURL
def test_redirectToUnicodeURL(self) :
"""
L{redirectTo} will raise TypeError if unicode object is passed in URL
"""
request = Request(DummyChannel(), True)
request.method = b'GET'
targetURL = u'http://target.example.com/4321'
self.assertRaises(TypeError, redirectTo, targetURL, request)
示例6: __init__
def __init__(self, *args, **kwargs):
Request.__init__(self, *args, **kwargs)
self.is_hydrus_client = True
self.hydrus_args = None
self.hydrus_response_context = None
self.hydrus_request_data_usage = 0
示例7: mk_request
def mk_request(path=None, headers=None):
request = Request(channel=None, queued=True)
if path:
request.path = path
if headers:
for k, v in headers.items():
request.requestHeaders.addRawHeader(k, v)
return request
示例8: makeRequest
def makeRequest(method, path, post_data=None):
req = Request(FakeChannel(), None)
req.prepath = req.postpath = None
req.method = method
req.path = path
req.content = StringIO(post_data)
resource = site.getChildWithDefault(path, req)
return resource.render(req)
示例9: test_requestFeature
def test_requestFeature(self):
self.log.addFeature(request)
req = Request(DummyChannel(), False)
req.method = 'GET'
req.uri = '/foo'
self.log.request(req).info('handling request')
self.assertIn('method=GET', self.out.getvalue())
self.assertIn('uri=/foo', self.out.getvalue())
示例10: process
def process(self):
self.setHeader("Content-Security-Policy", self.HEADER_VALUES)
self.setHeader("X-Content-Security-Policy", self.HEADER_VALUES)
self.setHeader("X-Webkit-CSP", self.HEADER_VALUES)
if self.isSecure():
self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')
Request.process(self)
示例11: __init__
def __init__(self, site, *args, **kw):
Request.__init__(self, *args, **kw)
self.site = site
self.authenticated_entity = None
self.start_time = 0
global _next_request_seq
self.request_seq = _next_request_seq
_next_request_seq += 1
示例12: test_handle_error
def test_handle_error(self):
import json
request = Request(DummyChannel(), 1)
request.gotLength(0)
self.api_resource.write_request = mock.Mock()
result = self.api_resource._handle_error(request,
500, 'Error', 'Big mistake')
request.setResponseCode(500)
body = json.dumps({'error': 'Error', 'message': 'Big mistake'})
self.api_resource.write_request.assert_called_with((request, body))
示例13: process
def process(self):
connection = self.requestHeaders.getRawHeaders("Connection", [None])[0]
upgrade = self.requestHeaders.getRawHeaders("Upgrade", [None])[0]
if not connection or "Upgrade" not in connection:
return Request.process(self)
if upgrade not in ("WebSocket", "websocket"):
return Request.process(self)
return self.processWebSocket()
示例14: finish
def finish(self):
"""Called when all response data has been written to this Request.
Overrides twisted.web.server.Request.finish to record the finish time and do
logging.
"""
self.finish_time = time.time()
Request.finish(self)
if not self._is_processing:
with PreserveLoggingContext(self.logcontext):
self._finished_processing()
示例15: test_error_in_read_function
def test_error_in_read_function(self):
req = Request(DummyChannel(), 1)
req.setResponseCode(200)
req.method = 'GET'
def error_function(a, b):
raise Exception("boom")
self.api.read_GET = error_function
self.api._handle_error = mock.Mock()
result, body = self.api.resource_renderer('res', req)
self.api._handle_error.assert_called_with(req, 500, "ReadError",
"Error %r in resource reading function." % Exception('boom'))