本文整理汇总了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)
示例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
示例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)
示例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))
示例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
示例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)
示例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)
示例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
示例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)
示例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
示例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
示例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)
示例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
示例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)
示例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