本文整理汇总了Python中requests.structures.CaseInsensitiveDict.update方法的典型用法代码示例。如果您正苦于以下问题:Python CaseInsensitiveDict.update方法的具体用法?Python CaseInsensitiveDict.update怎么用?Python CaseInsensitiveDict.update使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests.structures.CaseInsensitiveDict
的用法示例。
在下文中一共展示了CaseInsensitiveDict.update方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: string_to_sign
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def string_to_sign(self, request):
h = CaseInsensitiveDict()
h.update(request.headers)
# Try to use
if b'x-amz-date' in h or 'x-amz-date' in h:
date = ''
else:
date = h.get('Date') or self._get_date()
request.headers['Date'] = date
# Set the date header
request.headers['Date'] = date
# A fix for the content type header extraction in python 3
# This have to be done because requests will try to set application/www-url-encoded herader
# if we pass bytes as the content, and the content-type is set with a key that is b'Content-Type' and not
# 'Content-Type'
content_type = ''
if b'Content-Type' in request.headers:
# Fix content type
content_type = h.get(b'Content-Type')
del request.headers[b'Content-Type']
request.headers['Content-Type'] = content_type
msg = [
request.method,
h.get(b'Content-MD5', '') or h.get('Content-MD5', ''),
content_type or h.get('Content-Type', ''),
date,
self._get_canonicalized_amz_headers(h) + self._get_canonicalized_resource(request)
]
return '\n'.join(msg)
示例2: string_to_sign
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def string_to_sign(self, request):
"""
Generates the string we need to sign on.
Params:
- request The request object
Returns
String ready to be signed on
"""
# We'll use case insensitive dict to store the headers
h = CaseInsensitiveDict()
# Add the hearders
h.update(request.headers)
# If we have an 'x-amz-date' header,
# we'll try to use it instead of the date
if b'x-amz-date' in h or 'x-amz-date' in h:
date = ''
else:
# No x-amz-header, we'll generate a date
date = h.get('Date') or self._get_date()
# Set the date header
request.headers['Date'] = date
# A fix for the content type header extraction in python 3
# This have to be done because requests will try to set
# application/www-url-encoded header if we pass bytes as the content,
# and the content-type is set with a key that is b'Content-Type' and
# not 'Content-Type'
content_type = ''
if b'Content-Type' in request.headers:
# Fix content type
content_type = h.get(b'Content-Type')
del request.headers[b'Content-Type']
request.headers['Content-Type'] = content_type
# The string we're about to generate
# There's more information about it here:
# http://docs.aws.amazon.com/AmazonS3/latest/dev/
# RESTAuthentication.html#ConstructingTheAuthenticationHeader
msg = [
# HTTP Method
request.method,
# MD5 If provided
h.get(b'Content-MD5', '') or h.get('Content-MD5', ''),
# Content type if provided
content_type or h.get('Content-Type', ''),
# Date
date,
# Canonicalized special amazon headers and resource uri
self._get_canonicalized_amz_headers(h) +
self._get_canonicalized_resource(request)
]
# join with a newline and return
return '\n'.join(msg)
示例3: send_document
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def send_document(url, data, timeout=10, *args, **kwargs):
"""Helper method to send a document via POST.
Additional ``*args`` and ``**kwargs`` will be passed on to ``requests.post``.
:arg url: Full url to send to, including protocol
:arg data: POST data to send (dict)
:arg timeout: Seconds to wait for response (defaults to 10)
:returns: Tuple of status code (int or None) and error (exception class instance or None)
"""
logger.debug("send_document: url=%s, data=%s, timeout=%s", url, data, timeout)
headers = CaseInsensitiveDict({
'User-Agent': USER_AGENT,
})
if "headers" in kwargs:
# Update from kwargs
headers.update(kwargs.get("headers"))
kwargs.update({
"data": data, "timeout": timeout, "headers": headers
})
try:
response = requests.post(url, *args, **kwargs)
logger.debug("send_document: response status code %s", response.status_code)
return response.status_code, None
except RequestException as ex:
logger.debug("send_document: exception %s", ex)
return None, ex
示例4: DDWRT
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
class DDWRT(Router):
def __init__(self, conf, hostnames):
self.hostnames = CaseInsensitiveDict()
self.hostnames.update(hostnames)
self.conf = conf
self.auth = self.conf.auth()
def clients(self):
""" Receives all currently logged in users in a wifi network.
:rtype : list
:return: Returns a list of dicts, containing the following keys: mac, ipv4, seen, hostname
"""
clients = self._get_clients_raw()
clients_json = []
for client in clients:
client_hostname_from_router = client[0]
client_ipv4 = client[1].strip()
client_mac = client[2].strip().upper()
client_hostname = self.hostnames.get(client_mac, client_hostname_from_router).strip()
client_connections = int(client[3].strip())
# Clients with less than 20 connections are considered offline
if client_connections < 20:
continue
clients_json.append({
'mac': client_mac,
'ipv4': client_ipv4,
'seen': int(time.time()),
'hostname': client_hostname,
})
logger.debug('The router got us {} clients.'.format(len(clients_json)))
logger.debug(str(clients_json))
return clients_json
def _get_clients_raw(self):
info_page = self.conf.internal()
response = requests.get(info_page, auth=self.auth)
logger.info('Got response from router with code {}.'.format(response.status_code))
return DDWRT._convert_to_clients(response.text) or []
@staticmethod
def _convert_to_clients(router_info_all):
# Split router info in lines and filter empty info
router_info_lines = filter(None, router_info_all.split("\n"))
# Get key / value of router info
router_info_items = dict()
for item in router_info_lines:
key, value = item[1:-1].split("::") # Remove curly braces and split
router_info_items[key.strip()] = value.strip()
# Get client info as a list
arp_table = utils.groupn(router_info_items['arp_table'].replace("'", "").split(","), 4)
dhcp_leases = utils.groupn(router_info_items['dhcp_leases'].replace("'", "").split(","), 5)
return arp_table if (len(arp_table) > 0) else []
示例5: _check_creds
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def _check_creds(self, creds):
d = CaseInsensitiveDict()
if isinstance(creds, dict):
d.update(creds)
elif isinstance(creds, basestring):
if os.path.exists(creds):
creds = file(creds, "r").read()
for line in creds.splitlines():
if ":" in line:
k, v = line.split(":", 1)
d[k.strip()] = v.strip()
else:
raise TypeError("unsupported type for credentials data")
if "companyId" not in d and "CID" in d:
d["companyId"] = d["CID"]
if "companyId" in d and not "psk" in d:
raise ValueError("psk is required when companyId is provided")
elif "psk" in d and not "companyId" in d:
raise ValueError("companyId is required when psk is provided")
elif "companyId" in d and "psk" in d:
return {"companyId": int(d["companyId"]), "psk": str(d["psk"])}
elif "loginSessionId" in d and not "profileId" in d:
raise ValueError("profileId is required when loginSessionId is " "provided")
elif "profileId" in d and not "loginSessionId" in d:
raise ValueError("loginSessionId is required when profileId is " "provided")
elif "loginSessionId" in d and "profileId" in d:
return {"loginSessionId": str(d["loginSessionId"]), "profileId": int(d["profileId"])}
else:
raise ValueError("either companyId+psk or " "loginSessionId+profileId must be provided")
示例6: MockResponse
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
class MockResponse(object):
"""
Mock response object with a status code and some content
"""
def __init__(self, status_code, content=None, headers=None):
self.status_code = status_code
self.content = content or ''
self.headers = CaseInsensitiveDict()
if headers:
self.headers.update(headers)
def raise_for_status(self):
http_error_msg = ''
if 400 <= self.status_code < 500:
http_error_msg = '%s Client Error: ...' % self.status_code
elif 500 <= self.status_code < 600:
http_error_msg = '%s Server Error: ...' % self.status_code
if http_error_msg:
raise requests.HTTPError(http_error_msg, response=self)
def json(self, **kwargs):
return json.loads(self.content)
示例7: test_preserve_last_key_case
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def test_preserve_last_key_case(self):
cid = CaseInsensitiveDict({"Accept": "application/json", "user-Agent": "requests"})
cid.update({"ACCEPT": "application/json"})
cid["USER-AGENT"] = "requests"
keyset = frozenset(["ACCEPT", "USER-AGENT"])
assert frozenset(i[0] for i in cid.items()) == keyset
assert frozenset(cid.keys()) == keyset
assert frozenset(cid) == keyset
示例8: test_update
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def test_update(self):
cid = CaseInsensitiveDict()
cid["spam"] = "blueval"
cid.update({"sPam": "notblueval"})
self.assertEqual(cid["spam"], "notblueval")
cid = CaseInsensitiveDict({"Foo": "foo", "BAr": "bar"})
cid.update({"fOO": "anotherfoo", "bAR": "anotherbar"})
self.assertEqual(len(cid), 2)
self.assertEqual(cid["foo"], "anotherfoo")
self.assertEqual(cid["bar"], "anotherbar")
示例9: test_update
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def test_update(self):
cid = CaseInsensitiveDict()
cid["spam"] = "blueval"
cid.update({"sPam": "notblueval"})
assert cid["spam"] == "notblueval"
cid = CaseInsensitiveDict({"Foo": "foo", "BAr": "bar"})
cid.update({"fOO": "anotherfoo", "bAR": "anotherbar"})
assert len(cid) == 2
assert cid["foo"] == "anotherfoo"
assert cid["bar"] == "anotherbar"
示例10: test_update
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def test_update(self):
cid = CaseInsensitiveDict()
cid['spam'] = 'blueval'
cid.update({'sPam': 'notblueval'})
assert cid['spam'] == 'notblueval'
cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})
cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})
assert len(cid) == 2
assert cid['foo'] == 'anotherfoo'
assert cid['bar'] == 'anotherbar'
示例11: test_update
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def test_update(self):
cid = CaseInsensitiveDict()
cid['spam'] = 'blueval'
cid.update({'sPam': 'notblueval'})
self.assertEqual(cid['spam'], 'notblueval')
cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})
cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})
self.assertEqual(len(cid), 2)
self.assertEqual(cid['foo'], 'anotherfoo')
self.assertEqual(cid['bar'], 'anotherbar')
示例12: request
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def request(self, method, url, accept_json=False, headers=None, params=None, json=None, data=None, files=None,
**kwargs):
full_url = self.url + url
input_headers = _remove_null_values(headers) if headers else {}
headers = CaseInsensitiveDict({'user-agent': 'watson-developer-cloud-python-' + __version__})
if accept_json:
headers['accept'] = 'application/json'
headers.update(input_headers)
# Remove keys with None values
params = _remove_null_values(params)
json = _remove_null_values(json)
data = _remove_null_values(data)
files = _remove_null_values(files)
# Support versions of requests older than 2.4.2 without the json input
if not data and json is not None:
data = json_import.dumps(json)
headers.update({'content-type': 'application/json'})
auth = None
if self.username and self.password:
auth = (self.username, self.password)
if self.api_key is not None:
if params is None:
params = {}
if url.startswith('https://gateway-a.watsonplatform.net/calls'):
params['apikey'] = self.api_key
else:
params['api_key'] = self.api_key
response = requests.request(method=method, url=full_url, cookies=self.jar, auth=auth, headers=headers,
params=params, data=data, files=files, **kwargs)
if 200 <= response.status_code <= 299:
if accept_json:
response_json = response.json()
if 'status' in response_json and response_json['status'] == 'ERROR':
response.status_code = 400
error_message = 'Unknown error'
if 'statusInfo' in response_json:
error_message = response_json['statusInfo']
if error_message == 'invalid-api-key':
response.status_code = 401
raise WatsonException('Error: ' + error_message)
return response_json
return response
else:
if response.status_code == 401:
error_message = 'Unauthorized: Access is denied due to invalid credentials'
else:
error_message = self._get_error_message(response)
raise WatsonException(error_message)
示例13: test_preserve_last_key_case
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def test_preserve_last_key_case(self):
cid = CaseInsensitiveDict({
'Accept': 'application/json',
'user-Agent': 'requests',
})
cid.update({'ACCEPT': 'application/json'})
cid['USER-AGENT'] = 'requests'
keyset = frozenset(['ACCEPT', 'USER-AGENT'])
assert frozenset(i[0] for i in cid.items()) == keyset
assert frozenset(cid.keys()) == keyset
assert frozenset(cid) == keyset
示例14: http_get
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def http_get(self, url, headers=None):
"""
returns (status, header, content)
status: int
header: dict
content: string
"""
hdrs = CaseInsensitiveDict()
if headers:
hdrs.update(headers)
if not 'user-agent' in hdrs:
hdrs['user-agent'] = USER_AGENT
print "http_get:", url
r = requests.get(url, headers=hdrs)
return (r.status_code, r.headers, r.text)
示例15: generate_request
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import update [as 别名]
def generate_request(method, url, body):
"""
Generate our own custom request, so we can calculate digest auth.
"""
method = method.upper()
url = url
files = []
json_string = None
headers = CaseInsensitiveDict({
'Accept': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'keep-alive',
'Content-Type': 'application/json',
'User-Agent': 'stormpath-flask/0.4.4 flask/0.10.1 stormpath-sdk-python/2.4.5 python/2.7.6 Linux/LinuxMint (Linux-3.13.0-37-generic-x86_64-with-LinuxMint-17.1-rebecca)'
})
if body:
headers.update({'Content-Length': str(len(json.dumps(body)))})
params = OrderedDict()
auth = Sauthc1Signer(
id=os.environ.get('STORMPATH_API_KEY_ID'),
secret=os.environ.get('STORMPATH_API_KEY_SECRET'))
cookies = RequestsCookieJar()
hooks = {'response': []}
pr = PreparedRequest()
if body:
json_body = json.dumps(body)
else:
json_body = None
pr.prepare(
method=method.upper(),
url=url,
files=files,
data=json_body,
json=json_string,
headers=headers,
params=params,
auth=auth,
cookies=cookies,
hooks=hooks,
)
return pr