本文整理汇总了Python中requests.structures.CaseInsensitiveDict.items方法的典型用法代码示例。如果您正苦于以下问题:Python CaseInsensitiveDict.items方法的具体用法?Python CaseInsensitiveDict.items怎么用?Python CaseInsensitiveDict.items使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests.structures.CaseInsensitiveDict
的用法示例。
在下文中一共展示了CaseInsensitiveDict.items方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: assert_request_equal
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def assert_request_equal(self, expected, real_request):
method, path = expected[:2]
if urlparse(path).scheme:
match_path = real_request["full_path"]
else:
match_path = real_request["path"]
self.assertEqual((method, path), (real_request["method"], match_path))
if len(expected) > 2:
body = expected[2]
real_request["expected"] = body
err_msg = "Body mismatch for %(method)s %(path)s, " "expected %(expected)r, and got %(body)r" % real_request
self.orig_assertEqual(body, real_request["body"], err_msg)
if len(expected) > 3:
headers = CaseInsensitiveDict(expected[3])
for key, value in headers.items():
real_request["key"] = key
real_request["expected_value"] = value
real_request["value"] = real_request["headers"].get(key)
err_msg = (
"Header mismatch on %(key)r, "
"expected %(expected_value)r and got %(value)r "
"for %(method)s %(path)s %(headers)r" % real_request
)
self.orig_assertEqual(value, real_request["value"], err_msg)
real_request["extra_headers"] = dict(
(key, value) for key, value in real_request["headers"].items() if key not in headers
)
if real_request["extra_headers"]:
self.fail(
"Received unexpected headers for %(method)s " "%(path)s, got %(extra_headers)r" % real_request
)
示例2: assert_request_equal
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def assert_request_equal(self, expected, real_request):
method, path = expected[:2]
if urlparse(path).scheme:
match_path = real_request['full_path']
else:
match_path = real_request['path']
self.assertEqual((method, path), (real_request['method'],
match_path))
if len(expected) > 2:
body = expected[2]
real_request['expected'] = body
err_msg = 'Body mismatch for %(method)s %(path)s, ' \
'expected %(expected)r, and got %(body)r' % real_request
self.orig_assertEqual(body, real_request['body'], err_msg)
if len(expected) > 3:
headers = CaseInsensitiveDict(expected[3])
for key, value in headers.items():
real_request['key'] = key
real_request['expected_value'] = value
real_request['value'] = real_request['headers'].get(key)
err_msg = (
'Header mismatch on %(key)r, '
'expected %(expected_value)r and got %(value)r '
'for %(method)s %(path)s %(headers)r' % real_request)
self.orig_assertEqual(value, real_request['value'],
err_msg)
real_request['extra_headers'] = dict(
(key, value) for key, value in real_request['headers'].items()
if key not in headers)
if real_request['extra_headers']:
self.fail('Received unexpected headers for %(method)s '
'%(path)s, got %(extra_headers)r' % real_request)
示例3: test_preserve_last_key_case
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [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
示例4: set_extra_headers
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def set_extra_headers(self, headers):
header_dict = CaseInsensitiveDict(headers)
if 'Reply-To' in header_dict:
self.data["ReplyTo"] = header_dict.pop('Reply-To')
self.data["Headers"] = [
{"Name": key, "Value": value}
for key, value in header_dict.items()
]
示例5: test_preserve_key_case
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def test_preserve_key_case(self):
cid = CaseInsensitiveDict({
'Accept': 'application/json',
'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
示例6: SSDPResponse
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
class SSDPResponse(object):
"""A container class for received SSDP responses."""
def __init__(self, response):
"""Initializes the SSDPResponse instance based on a response string"""
super(BasicSSDPServiceDiscoverer.SSDPResponse, self).__init__()
# Initialize fields
self.Location = None
self.USN = None
self.ST = None
self.Headers = CaseInsensitiveDict()
# Parse response
self._fromString(response)
def _fromString(self, str):
"""Parses a response string and assigns values to the SSDPResponse object.
:param str str: The string to parse."""
# Lazy method to parse all http-headers
h = CaseInsensitiveDict({k.lower(): v for k, v in dict(re.findall(r'(?P<name>.*?): (?P<value>.*?)\r\n', str)).items()})
self.Headers = h
# Set major fields
if 'location' in h:
self.Location = h['location']
if 'USN' in h:
self.USN = h['USN']
if 'ST' in h:
self.ST = h['ST']
def __repr__(self):
return '<SSDPResponse from %s at %s; Headers: %s>' % (self.USN, self.Location, self.Headers.__repr__())
def __hash__(self):
if self.USN is not None:
return hash(self.USN)
return hash(tuple(self.Headers.items()))
def __eq__(self, other):
if self is not None and other is None:
return False
if not isinstance(other, self.__class__):
return False
return hash(self) == hash(other)
def __ne__(self, other):
return not self.__eq__(other)
示例7: test_preserve_last_key_case
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [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: verify_signature
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def verify_signature(self, query_parameters):
"""Verify the signature provided with the query parameters.
http://docs.shopify.com/api/tutorials/oauth
example usage::
from shopify_trois import Credentials
from shopify_trois.engines import Json as Shopify
from urllib.parse import parse_qsl
credentials = Credentials(
api_key='your_api_key',
scope=['read_orders'],
secret='your_app_secret'
)
shopify = Shopify(shop_name="your_store_name", credentials=\
credentials)
query_parameters = parse_qsl("code=238420989938cb70a609f6ece2e2586\
b&shop=yourstore.myshopify.com×tamp=1373382939&\
signature=6fb122e33c21851c465345b8cb97245e")
if not shopify.verify_signature(query_parameters):
raise Exception("invalid signature")
credentials.code = dict(query_parameters).get('code')
shopify.setup_access_token()
:returns: Returns True if the signature is valid.
"""
params = CaseInsensitiveDict(query_parameters)
signature = params.pop("signature", None)
calculated = ["%s=%s" % (k, v) for k, v in params.items()]
calculated.sort()
calculated = "".join(calculated)
calculated = "{secret}{calculated}".format(
secret=self.credentials.secret,
calculated=calculated
)
md5 = hashlib.md5()
md5.update(calculated.encode('utf-8'))
produced = md5.hexdigest()
return produced == signature
示例9: _prepare_request
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def _prepare_request(self, command, json=True, opcode_name='command',
fetch_list=False, **kwargs):
params = CaseInsensitiveDict(**kwargs)
params.update({
'apiKey': self.key,
opcode_name: command,
})
if json:
params['response'] = 'json'
if 'page' in kwargs or fetch_list:
params.setdefault('pagesize', PAGE_SIZE)
if 'expires' not in params and self.expiration.total_seconds() >= 0:
params['signatureVersion'] = '3'
tz = pytz.utc
expires = tz.localize(datetime.utcnow() + self.expiration)
params['expires'] = expires.astimezone(tz).strftime(EXPIRES_FORMAT)
kind = 'params' if self.method == 'get' else 'data'
return kind, dict(params.items())
示例10: test_preserve_key_case
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def test_preserve_key_case(self):
cid = CaseInsensitiveDict({"Accept": "application/json", "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
示例11: tizgmusicproxy
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
#.........这里部分代码省略.........
""" Return the current track's year of publication.
"""
logging.info("current_song_year")
song = self.now_playing_song
year = 0
if song:
try:
year = song['year']
logging.info("track year %s", year)
except KeyError:
logging.info("year : not found")
else:
logging.info("current_song_year : not found")
return year
def clear_queue(self):
""" Clears the playback queue.
"""
self.queue = list()
self.queue_index = -1
def enqueue_artist(self, arg):
""" Search the user's library for tracks from the given artist and adds
them to the playback queue.
:param arg: an artist
"""
try:
self.__update_local_library()
artist = None
if arg not in self.library.keys():
for name, art in self.library.iteritems():
if arg.lower() in name.lower():
artist = art
print_wrn("[Google Play Music] '{0}' not found. " \
"Playing '{1}' instead." \
.format(arg.encode('utf-8'), \
name.encode('utf-8')))
break
if not artist:
# Play some random artist from the library
random.seed()
artist = random.choice(self.library.keys())
artist = self.library[artist]
print_wrn("[Google Play Music] '{0}' not found. "\
"Feeling lucky?." \
.format(arg.encode('utf-8')))
else:
artist = self.library[arg]
tracks_added = 0
for album in artist:
tracks_added += self.__enqueue_tracks(artist[album])
print_wrn("[Google Play Music] Playing '{0}'." \
.format(to_ascii(artist)))
self.__update_play_queue_order()
except KeyError:
raise KeyError("Artist not found : {0}".format(arg))
def enqueue_album(self, arg):
""" Search the user's library for albums with a given name and adds
them to the playback queue.
"""
try:
示例12: complete
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
#.........这里部分代码省略.........
if oldart['titre'].lower() in table_concordance:
new_art = table_concordance[oldart['titre']]
if 'suppr' in new_art:
c, a = oldarts.pop(0)
oldartids.remove(c)
if olddepot:
log("DEBUG: Marking art %s as supprimé (thanks to concordance table)" % c)
a["order"] = order
order += 1
write_json(a)
continue
# as a backup, use the detected status to wait for a non-deleted article
if re_suppr.match(oldart['statut']):
c, a = oldarts.pop(0)
oldartids.remove(c)
if olddepot:
log("DEBUG: Marking art %s as supprimé (recovered)" % c)
a["order"] = order
order += 1
write_json(a)
else:
break
except Exception as e:
print("ERROR: Problem while renumbering articles", line, "\n", oldart, "\n", type(e), e, file=sys.stderr)
exit()
# detect matching errors
if oldart['titre'] in table_concordance:
new_art = table_concordance[oldart['titre']]
if new_art.lower() != line['titre'].lower():
print("ERROR: true concordance is different: when parsing article '%s', we matched it with '%s' which should be matched to '%s' (from concordance table) " % (line['titre'] , oldart['titre'], new_art))
match = None
for oldart_title, newart_title in table_concordance.items():
if newart_title.lower() == line['titre'].lower():
match = oldart_title
print(' -> it should have been matched with article %s' % oldart_title)
break
else:
print(' -> it should have been deleted')
# if article not matching but here in the concordance table, introduce it as a new one
# since it can correspond to an article deleted by the Senate in Nouvelle lecture
# or an article introduced in CMP hémicycle
# /!\ this can only happen during a lecture définitive or a CMP hémicycle
if (step.get('stage') == 'l. définitive' or (
step.get('step') == 'hemicycle' and step.get('stage') == 'CMP')
) and match:
log("DEBUG: Marking art %s as nouveau" % line['titre'])
if "section" in line and cursec['id'] != line["section"]:
line["section"] = cursec["id"]
a = line
a["order"] = order
a["status"] = "nouveau"
if a['titre'] != match:
a['newtitre'] = a['titre']
a['titre'] = match
order += 1
write_json(a)
continue
else:
exit()
log("DEBUG: article '%s' matched with old article '%s'" % (line['titre'], oldart['titre']))
oldtxt = get_alineas_text(oldart["alineas"])
示例13: sniffit
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
def sniffit():
"""
Perform an HTTP/HTTPS request to the address that the user specifid
:return:
TODO Make the Google Verification a separate module with annotion
"""
parsed_url = urlparse(request.json["url"])
app.logger.info(request.remote_addr + " " + parsed_url.netloc)
# Processing the headers to be sent to the URL that the user defined in the interface.
# What we are doing here is making sure the the user can't override some headers that we want to force such as
# X-Forwarded-For.
request_headers = CaseInsensitiveDict({header["key"]: header["value"] for header in request.json["headers"]})
request_headers["X-Forwarded-For"] = request.remote_addr
request_headers["X-Anti-Abuse"] = app.config.get("ABUSE_CONTACT")
request_headers = {string.capwords(k, "-"): v for (k, v) in request_headers.items()}
# Request Parameters
if type(request.json["parameters"]) is list:
request_parameters = "&".join([cgi.escape(header["key"])+"="+cgi.escape(header["value"]) for header in request.json["parameters"]])
else:
request_parameters = request.json["parameters"]
# Base Response JSON
response_json = {'success': False, 'sniffed': None, 'messages': []}
try:
if string.lower(request.json["method"]) in ["get", "head", "options"]:
response = requests.request(request.json["method"], request.json["url"], verify=False,
params=request_parameters, headers=request_headers)
else:
response = requests.request(request.json["method"], request.json["url"],
verify=False, data=request_parameters, headers=request_headers)
# I prefer to have the capitalized headers in the frontend
# This will convert the headers from 'content-type' to 'Content-Type'
response_headers = {string.capwords(k, "-"): v for (k, v) in response.headers.items()}
# This is for the adrministrators only so there is no need for the end-user to see this
request_headers.pop("X-Anti-Abuse")
request_headers.pop("X-Forwarded-For")
# Create a history of redirects to inform the user
redirections = [{"url": redirect.headers["location"]} for redirect in response.history]
# Geo Location
ipaddress = socket.gethostbyname(parsed_url.netloc)
geolocation_response = requests.get("http://ip-api.com/json/" + ipaddress);
response_json["success"] = True
response_json["showRecaptcha"] = recaptcha_handler.is_token_invalid()
response_json["sniffed"] = {
'headers': {
'response': response_headers,
'request': request_headers
},
'ipaddress': ipaddress,
'geolocation': geolocation_response.json(),
'ssl': None,
'redirect': redirections,
'body': base64.b64encode(cgi.escape(response.text.encode("UTF-8"))),
'size': response.headers.get("content-length", False),
'ssize': len(response.text.encode("UTF-8")),
'elapsed': response.elapsed.total_seconds(),
'status': {
"reason": response.reason,
"code": str(response.status_code)
}
}
except Exception as e:
raise RequestFailedException(repr(e))
return jsonify(response_json)
示例14: MockRestURI
# 需要导入模块: from requests.structures import CaseInsensitiveDict [as 别名]
# 或者: from requests.structures.CaseInsensitiveDict import items [as 别名]
class MockRestURI(object):
"""Representation of a mock URI."""
def __init__(self, uri_dict):
self._uri_dict = uri_dict
self.name = uri_dict.get('name', None)
self.fullpath = uri_dict['request']['path']
self._regexp = False
self.path = urlparse.urlparse(self.fullpath).path
self.querystring = urlparse.parse_qs(
urlparse.urlparse(self.fullpath).query,
keep_blank_values=True
)
self.method = uri_dict['request'].get('method', None)
self.headers = CaseInsensitiveDict(uri_dict['request'].get('headers', {}))
self.return_code = int(uri_dict['response'].get('code', '200'))
self.request_content_type = self.headers.get('Content-Type', '')
self.response_location = uri_dict['response'].get('location', None)
self.response_content = uri_dict['response'].get('content', "")
self.wait = float(uri_dict['response'].get('wait', 0.0))
self.request_data = uri_dict['request'].get('data', None)
self.encoding = uri_dict['request'].get("encoding", None)
self.response_headers = uri_dict['response'].get("headers", {})
def match(self, request):
"""Does this URI match the request?"""
# Match HTTP verb - GET, POST, PUT, DELETE, etc.
if self.method is not None:
if request.command.lower() != self.method.lower():
return False
# Match path
if self.path != urlparse.urlparse(request.path).path:
return False
# Match querystring
if request.querystring() != self.querystring:
return False
# Match headers
if self.headers is not None:
for header_var, header_value in self.headers.items():
request_headers = CaseInsensitiveDict(request.headers)
if request_headers.get(header_var) is None:
return False
req_maintext, req_pdict = cgi.parse_header(request_headers.get(header_var))
mock_maintext, mock_pdict = cgi.parse_header(header_value)
if "boundary" in req_pdict and "boundary" in mock_pdict:
req_pdict['boundary'] = "xxx"
mock_pdict['boundary'] = "xxx"
if req_maintext != mock_maintext:
return False
if mock_pdict != {}:
if req_pdict != mock_pdict:
return False
# Match processed request data
if self.request_data is not None:
# Check if exact match before parsing
if request.body != self.request_data:
if self.request_content_type.startswith("application/json"):
if json.loads(request.body) != json.loads(self.request_data):
return False
elif self.request_content_type.startswith("application/x-www-form-urlencoded"):
if parse_qsl_as_dict(request.body) != parse_qsl_as_dict(self.request_data):
return False
elif self.request_content_type.startswith('application/xml'):
actual_request_data_root = etree.fromstring(request.body)
mock_request_data_root = etree.fromstring(self.request_data)
if not xml_elements_equal(actual_request_data_root, mock_request_data_root):
return False
elif self.request_content_type.startswith("multipart/form-data"):
ctype, pdict = cgi.parse_header(request.headers.get('Content-Type'))
req_multipart = cgi.parse_multipart(
io.BytesIO(request.body.encode('utf8')),
{x: y.encode('utf8') for x, y in pdict.items()}
)
ctype, pdict = cgi.parse_header(self.headers.get('Content-Type'))
mock_multipart = cgi.parse_multipart(
io.BytesIO(self.request_data.encode('utf8')),
{x: y.encode('utf8') for x, y in pdict.items()}
)
return mock_multipart == req_multipart
else:
if request.body != self.request_data:
return False
return True
def querystring_string(self):
# TODO : Refactor this and docstring.
query = ''
for key in self.querystring.keys():
#.........这里部分代码省略.........