• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python server.Request类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.web.server.Request的典型用法代码示例。如果您正苦于以下问题:Python Request类的具体用法?Python Request怎么用?Python Request使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Request类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:spaceone,项目名称:univention-management-console,代码行数:26,代码来源:request.py


示例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""
开发者ID:alex-docker,项目名称:flocker,代码行数:33,代码来源:testtools.py


示例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()
开发者ID:DoubleMalt,项目名称:synapse,代码行数:28,代码来源:site.py


示例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)
开发者ID:codecats,项目名称:kitty,代码行数:33,代码来源:test_websockets.py


示例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)
开发者ID:daweasel27,项目名称:PhobiaEnemy,代码行数:8,代码来源:test_util.py


示例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
开发者ID:sttollgrin,项目名称:hydrus,代码行数:8,代码来源:HydrusServer.py


示例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
开发者ID:praekelt,项目名称:go-optouts-api,代码行数:8,代码来源:test_auth.py


示例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)
开发者ID:adcaes,项目名称:eventer_api,代码行数:8,代码来源:make_request.py


示例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())
开发者ID:dreid,项目名称:twixxy,代码行数:9,代码来源:test_features.py


示例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)
开发者ID:phss,项目名称:pixelated-user-agent,代码行数:9,代码来源:site.py


示例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
开发者ID:rubo77,项目名称:synapse,代码行数:9,代码来源:site.py


示例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))
开发者ID:DmitryLoki,项目名称:gorynych,代码行数:10,代码来源:test_base_resource.py


示例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()
开发者ID:thomasvs,项目名称:txWebSocket,代码行数:11,代码来源:websocket.py


示例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()
开发者ID:DoubleMalt,项目名称:synapse,代码行数:11,代码来源:site.py


示例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'))
开发者ID:DmitryLoki,项目名称:gorynych,代码行数:11,代码来源:test_base_resource.py


示例16: finish

 def finish(self):
     """
     Event received when the request is finished,
     for WebsocketTransport only.
     Pass that event to the transport, for processing extensions.
     """
     if self.transport.__class__ == WebsocketTransport:
         self.transport.finish()
     if not self._disconnected:
         ## FIXME: use notifyFinished?
         Request.finish(self)
开发者ID:aprilmay,项目名称:txWebSocket,代码行数:11,代码来源:websocket.py


示例17: process

    def process(self):
        upgrade = self.requestHeaders.getRawHeaders("Upgrade")
        if not upgrade or upgrade[0] not in ("WebSocket", "websocket"):
            return Request.process(self)

        connection = self.requestHeaders.getRawHeaders("Connection")
        if not connection or "Upgrade" not in [
                        c.lstrip() for c in connection[0].split(',')]:
            return Request.process(self)

        return self.processWebSocket()
开发者ID:aprilmay,项目名称:txWebSocket,代码行数:11,代码来源:websocket.py


示例18: 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.lower():
            return Request.process(self)

        if not upgrade or upgrade.lower() != "websocket":
            return Request.process(self)

        return self.processWebSocket()
开发者ID:sociam,项目名称:indx,代码行数:11,代码来源:websocket.py


示例19: process

    def process(self):
        self.setHeader('Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Content-Security-Policy', self.CSP_HEADER_VALUES)
        self.setHeader('X-Webkit-CSP', self.CSP_HEADER_VALUES)
        self.setHeader('X-Frame-Options', 'SAMEORIGIN')
        self.setHeader('X-XSS-Protection', '1; mode=block')
        self.setHeader('X-Content-Type-Options', 'nosniff')

        if self.isSecure():
            self.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains')

        Request.process(self)
开发者ID:pixelated,项目名称:pixelated-user-agent,代码行数:12,代码来源:site.py


示例20: getTextOfPage

def getTextOfPage(root, page, args=None, return_request=False):
    """This perpetrates several awful hacks."""
    if args is not None:
        page += '?' + urllib.urlencode(args)
    channel = DummyChannel()
    channel.site = Site(root)
    r = Request(channel, 0)
    r.content = StringIO()
    r.requestReceived("GET", "/" + page, "1.1")
    if return_request:
        return channel.transport.written.getvalue(), r
    else:
        return channel.transport.written.getvalue()
开发者ID:chevah,项目名称:pydoctor,代码行数:13,代码来源:test_server.py



注:本文中的twisted.web.server.Request类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python server.Site类代码示例发布时间:2022-05-27
下一篇:
Python resource.Resource类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap