当前位置: 首页>>代码示例>>Python>>正文


Python Headers.addRawHeader方法代码示例

本文整理汇总了Python中twisted.web.http_headers.Headers.addRawHeader方法的典型用法代码示例。如果您正苦于以下问题:Python Headers.addRawHeader方法的具体用法?Python Headers.addRawHeader怎么用?Python Headers.addRawHeader使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.web.http_headers.Headers的用法示例。


在下文中一共展示了Headers.addRawHeader方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: http_get

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
def http_get(reactor, url, accept=None):
    agent = client.Agent(reactor)
    headers = Headers()
    if accept is not None:
        headers.addRawHeader('Accept', str(accept))
    d = agent.request('GET', url, headers=headers)
    return _handle_agent_response(d)
开发者ID:nunb,项目名称:shinysdr,代码行数:9,代码来源:testutil.py

示例2: _make_request

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
    def _make_request(self):
        metrics = []
        for x in xrange(HTTP_BATCH):
            if not self._mq:
                break
            metrics.append(self._mq.popleft())
        if not metrics:
            return defer.succeed(None)

        serialized_metrics = json.dumps({"metrics": metrics})
        body_writer = StringProducer(serialized_metrics)

        headers = Headers({
            'User-Agent': ['Zenoss Metric Publisher: %s' % self._agent_suffix],
            'Content-Type': ['application/json']})

        if self._needsAuth and not self._authenticated:
            log.info("Adding auth for metric http post %s", self._url)
            headers.addRawHeader('Authorization',
                                 basic_auth_string_content(self._username, self._password))

        d = self._agent.request(
            'POST', self._url, headers,
            body_writer)

        d.addCallbacks(self._metrics_published, errback=self._publish_failed,
        callbackArgs = [len(metrics), len(self._mq)], errbackArgs = [metrics])
        d.addCallbacks(self._response_finished, errback=self._publish_failed,
                       errbackArgs = [metrics])

        return d
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:33,代码来源:publisher.py

示例3: test_request

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
    def test_request(self, mock_request):
        self.patch_request.stop()
        args = ('GET', self.url)
        self.agent.request(*args)
        mock_request.assert_called_once_with(self.agent, *args + (None, None))
        mock_request.reset_mock()

        args = ('GET', self.url)
        data = 'foo'
        self.agent.request(*args, data=data)
        match_bodyProducer = Matcher(compare_bodyProducer, self.agent.bodyProducer(data))
        mock_request.assert_called_once_with(self.agent, *args + (None, match_bodyProducer))
        mock_request.reset_mock()

        headers = Headers()
        headers.addRawHeader('Content-Type', 'application/json')
        args = ('GET', self.url, headers)
        self.agent.request(*args, data='foo')
        match_bodyProducer = Matcher(compare_bodyProducer, self.agent.bodyProducer(data))
        mock_request.assert_called_once_with(self.agent, *args + (match_bodyProducer,))
        mock_request.reset_mock()

        headers = Headers()
        headers.addRawHeader('Content-Type', 'application/json')
        args = ('GET', self.url, headers, None)
        self.agent.request(*args)
        mock_request.assert_called_once_with(self.agent, *args)
开发者ID:pantheon-systems,项目名称:tx_clients,代码行数:29,代码来源:test_http.py

示例4: url_upload_data_async

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
def url_upload_data_async(url, files={}, data={}, progressCallback=None, doneCallback=None):

    def produce_finished(data):
        print 'produce finished',data
    def produce_error(error):
        print 'produce error', error

    producerDeferred = Deferred()
    producerDeferred.addCallback(produce_finished)
    producerDeferred.addErrback(produce_error)

    def receive_finished(data):
        print 'recieve finished', data
        doneCallback(data)

    def receive_error(error):
        Logger.error('Problem uploading file')
        print 'recieve error', error

    receiverDeferred = Deferred()
    receiverDeferred.addCallback(receive_finished)
    receiverDeferred.addErrback(receive_error)

    producer = MultiPartProducer(files, data, progressCallback, producerDeferred)
    receiver = StringReceiver(receiverDeferred)

    agent = Agent(reactor)
    headers = Headers({'User-Agent': ['Twisted Web Client Example']})
    headers.addRawHeader("Content-Type", "multipart/form-data; boundary=%s" % producer.boundary)

    requestDeffered = agent.request('POST', url, headers, producer)
    requestDeffered.addCallback(lambda response: response.deliverBody(receiver))
开发者ID:insiderr,项目名称:insiderr-app,代码行数:34,代码来源:http_utils.py

示例5: headers

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
 def headers(self):
     if not self.result:
         raise Exception("No result yet.")
     h = Headers()
     for i in self.result["headers"]:
         h.addRawHeader(*i)
     return h
开发者ID:DoubleMalt,项目名称:synapse,代码行数:9,代码来源:server.py

示例6: headers

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
    def headers(self, rawHeaders):
        # type: (RawHeaders) -> IMutableHTTPHeaders
        headers = Headers()
        for rawName, rawValue in rawHeaders:
            headers.addRawHeader(rawName, rawValue)

        return HTTPHeadersWrappingHeaders(headers=headers)
开发者ID:notoriousno,项目名称:klein,代码行数:9,代码来源:test_headers_compat.py

示例7: obtain_auth_token

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
 def obtain_auth_token(self):
     """Return a valid Microsoft Cognitive Services authentication
     token, obtained with the current subscription key if necessary.
     """
     start_time = time.time()
     if self.auth_token is None or self.token_expiry < start_time:
         headers = Headers()
         headers.addRawHeader('Ocp-Apim-Subscription-Key',
                              self.subscription_key)
         headers.addRawHeader('Content-Length', '0')
         response = yield self.agent.request(
             'POST', AUTH_URL, headers=headers)
         if response.code != 200:
             data = yield readBody(response)
             self.log.error(
                 'Could not authenticate to Microsoft Cognitive '
                 'Services: {data}', data=data)
             raise UserVisibleError(
                 'Could not authenticate to Microsoft Cognitive '
                 'Services. Try again later.')
         # Coerce the access token to a byte string to avoid problems
         # inside Twisted's header handling code down the line.
         self.auth_token = (
             (yield readBody(response)).strip().decode('ascii'))
         self.token_expiry = start_time + AUTH_TOKEN_TTL
     returnValue(self.auth_token)
开发者ID:kxz,项目名称:omnipresence,代码行数:28,代码来源:__init__.py

示例8: request

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
    def request(self, method, url, **kwargs):
        method = method.upper()

        # Join parameters provided in the URL
        # and the ones passed as argument.
        params = kwargs.get('params')
        if params:
            url = _combine_query_params(url, params)

        # Convert headers dictionary to
        # twisted raw headers format.
        headers = kwargs.get('headers')
        if headers:
            if isinstance(headers, dict):
                h = Headers({})
                for k, v in headers.iteritems():
                    if isinstance(v, str):
                        h.addRawHeader(k, v)
                    else:
                        h.setRawHeaders(k, v)

                headers = h
        else:
            headers = Headers({})

        # Here we choose a right producer
        # based on the parameters passed in.
        bodyProducer = None
        data = kwargs.get('data')
        files = kwargs.get('files')
        if files:
            # If the files keyword is present we will issue a
            # multipart/form-data request as it suits better for cases
            # with files and/or large objects.
            files = list(_convert_files(files))
            boundary = uuid.uuid4()
            headers.setRawHeaders(
                'content-type', [
                    'multipart/form-data; boundary=%s' % (boundary,)])
            if data:
                data = _convert_params(data)
            else:
                data = []

            bodyProducer = multipart.MultiPartProducer(
                data + files, boundary=boundary)
        elif data:
            # Otherwise stick to x-www-form-urlencoded format
            # as it's generally faster for smaller requests.
            if isinstance(data, (dict, list, tuple)):
                headers.setRawHeaders(
                    'content-type', ['application/x-www-form-urlencoded'])
                data = urlencode(data, doseq=True)
            bodyProducer = IBodyProducer(data)

        d = self._agent.request(
            method, url, headers=headers,
            bodyProducer=bodyProducer)

        return d
开发者ID:itsjustpiper,项目名称:treq,代码行数:62,代码来源:client.py

示例9: request

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
 def request(self, method, uri, headers=None, data=None):
     if data is not None:
         if headers is None:
             headers = Headers()
         headers.removeHeader('Content-Type')
         headers.addRawHeader('Content-Type', 'application/json; charset=utf-8')
     return BasicAgent.request(self, method, uri, headers, data)
开发者ID:pantheon-systems,项目名称:tx_clients,代码行数:9,代码来源:http.py

示例10: request

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
    def request(self, method, uri, headers=None, bodyProducer=None):
        """
        Issue a new request to the wrapped L{Agent}.

        Send a I{Cookie} header if a cookie for C{uri} is stored in
        L{CookieAgent.cookieJar}. Cookies are automatically extracted and
        stored from requests.

        If a C{'cookie'} header appears in C{headers} it will override the
        automatic cookie header obtained from the cookie jar.

        @see: L{Agent.request}
        """
        if headers is None:
            headers = Headers()
        lastRequest = _FakeUrllib2Request(uri)
        # Setting a cookie header explicitly will disable automatic request
        # cookies.
        if not headers.hasHeader('cookie'):
            self.cookieJar.add_cookie_header(lastRequest)
            cookieHeader = lastRequest.get_header('Cookie', None)
            if cookieHeader is not None:
                headers = headers.copy()
                headers.addRawHeader('cookie', cookieHeader)

        d = self._agent.request(method, uri, headers, bodyProducer)
        d.addCallback(self._extractCookies, lastRequest)
        return d
开发者ID:GunioRobot,项目名称:twisted,代码行数:30,代码来源:client.py

示例11: _baseHeaders

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
	def _baseHeaders(self):
		"""return a dictionary of the base headers needed in a peer request"""
		headers = Headers()
		headers.addRawHeader('Target',self.target)
		headers.addRawHeader('Signature',self._signature)

		return headers
开发者ID:doctorOb,项目名称:MQP,代码行数:9,代码来源:peerHandler.py

示例12: request

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
    def request(self, method, uri, headers=None, bodyProducer=None):
        parsedURI = client._parse(uri)
        
        host_addr = address.IPv4Address('TCP', parsedURI.host, parsedURI.port)
        
        
        # ripped from _AgentBase._requestWithEndpoint
        if headers is None:
            headers = Headers()
        if not headers.hasHeader('host'):
            headers = headers.copy()
            headers.addRawHeader(
                'host', self._computeHostValue(parsedURI.scheme, parsedURI.host,
                                               parsedURI.port))
        request = client.Request(method, parsedURI.path, headers, bodyProducer,
                                 persistent=False)

        c = ClientProtocol(request)
        
        # ouch
        self.root.putChild('', self.root)
        
        server = Site(self.root).buildProtocol(self.addr)
        loopbackAsync(server, c, host_addr, self.addr)
        return c.response.addBoth(self._done, c)
开发者ID:tomprince,项目名称:agentforhire,代码行数:27,代码来源:badhack.py

示例13: request

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
    def request(self, method, uri, headers=None, bodyProducer=None):
        """
        Issue a new request via the configured proxy.
        """

        if version >= Version('twisted', 13, 1, 0):
            parsed_uri = _URI.getFromBytes(uri)
            scheme = parsed_uri.scheme
            host = parsed_uri.host
            port = parsed_uri.port
        else:
            scheme, host, port, path = _parse(uri)
        request_path = uri

        d = self._connect(scheme, host, port)

        if headers is None:
            headers = Headers()
        if not headers.hasHeader('host'):
            # This is a lot of copying.  It might be nice if there were a bit
            # less.
            headers = Headers(dict(headers.getAllRawHeaders()))
            headers.addRawHeader(
                'host', self._computeHostValue(scheme, host, port))

        def cbConnected(proto):
            # NOTE: For the proxy case the path should be the full URI.
            return proto.request(
                Request(method, request_path, headers, bodyProducer))

        d.addCallback(cbConnected)
        return d
开发者ID:lazy404,项目名称:txsuds,代码行数:34,代码来源:twisted_transport.py

示例14: post

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
def post(url, data=None, on_created=None, on_error=None):
    errback = on_error or make_errback(frames_back=2)
    try:
        def handle_response(response):
            if response.code == 200:
                callback = partial(
                    _handle_post,
                    on_created=on_created,
                    on_error=errback)
                response.deliverBody(JsonReceiver.create(callback, errback))
            else:
                errback('returned %s' % response.code)

        agent = Agent(reactor)
        headers = Headers(get_auth_headers())
        headers.addRawHeader('Content-Type', 'application/json')
        if not data:
            data = {'dummy': 1}
        d = agent.request(
            'POST',
            add_params(url, rid=uuid4().hex),
            headers=headers,
            bodyProducer=JsonProducer(data) if data else None)
        d.addCallbacks(handle_response, errback)
    except Exception as ex:
        errback('error %s' % ex)
开发者ID:insiderr,项目名称:insiderr-app,代码行数:28,代码来源:post.py

示例15: encode_headers

# 需要导入模块: from twisted.web.http_headers import Headers [as 别名]
# 或者: from twisted.web.http_headers.Headers import addRawHeader [as 别名]
def encode_headers(headers):
    twisted_headers = Headers()
    for k, v in headers.items():
        key = k.encode('ascii', 'ignore')
        val = v.encode('ascii', 'ignore')
        twisted_headers.addRawHeader(key, val)
    return twisted_headers
开发者ID:JvanDalfsen,项目名称:calvin-base,代码行数:9,代码来源:http_client.py


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