本文整理汇总了Python中requests.compat.str函数的典型用法代码示例。如果您正苦于以下问题:Python str函数的具体用法?Python str怎么用?Python str使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了str函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_invalid_timeout
def test_invalid_timeout(self):
with pytest.raises(ValueError) as e:
requests.get(httpbin("get"), timeout=(3, 4, 5))
assert "(connect, read)" in str(e)
with pytest.raises(ValueError) as e:
requests.get(httpbin("get"), timeout="foo")
assert "must be an int or float" in str(e)
开发者ID:RRedwards,项目名称:requests,代码行数:8,代码来源:test_requests.py
示例2: line
def line(self):
"""Return Status-Line"""
original = self._orig.raw._original_response
return str('HTTP/{version} {status} {reason}'.format(
version='.'.join(str(original.version)),
status=original.status,
reason=original.reason
))
开发者ID:dai,项目名称:httpie,代码行数:8,代码来源:models.py
示例3: make_response_message
def make_response_message(response):
"""Make an `HTTPMessage` from `requests.models.Response`."""
encoding = response.encoding or 'ISO-8859-1'
original = response.raw._original_response
response_headers = response.headers
return HTTPMessage(
line='HTTP/{version} {status} {reason}'.format(
version='.'.join(str(original.version)),
status=original.status, reason=original.reason,),
headers=str(original.msg),
body=response.content.decode(encoding) if response.content else '',
content_type=response_headers.get('Content-Type'))
开发者ID:macro,项目名称:httpie,代码行数:12,代码来源:__main__.py
示例4: test_iter_lines
def test_iter_lines(self):
lines = (0, 2, 10, 100)
for i in lines:
r = get(httpbin('stream', str(i)), prefetch=False)
lines = list(r.iter_lines())
len_lines = len(lines)
self.assertEqual(i, len_lines)
# Test 'dangling' fragment in responses that do not terminate in
# a newline.
quote = (
'''Why will he not upon our fair request\n'''
'''Untent his person and share the air with us?'''
)
# Make a request and monkey-patch its contents
r = get(httpbin('get'))
r.raw = StringIO(quote)
# Make sure iter_lines doesn't chop the trailing bit
lines = '\n'.join(r.iter_lines())
self.assertEqual(lines, quote)
开发者ID:chipx86,项目名称:requests,代码行数:25,代码来源:test_requests.py
示例5: safe_str
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape')
开发者ID:royburns,项目名称:pyServerAPITest,代码行数:7,代码来源:test_QiuShiBaiKe.py
示例6: update_cookies
def update_cookies(cookies, resp):
if 'SNUID' not in cookies:
p = re.compile(r'(?<=SNUID=)\w+')
cookies['SNUID'] = p.findall(resp.text)[0]
suv = ''.join([str(int(time.time()*1000000) + random.randint(0, 1000))])
cookies['SUV'] = suv
return cookies
开发者ID:muzixinly,项目名称:wx_reader,代码行数:7,代码来源:wx_reader.py
示例7: test_iter_lines
def test_iter_lines(self):
lines = (0, 2, 10, 100)
for i in lines:
r = get(httpbin('stream', str(i)), prefetch=False)
lines = list(r.iter_lines())
len_lines = len(lines)
self.assertEqual(i, len_lines)
# Tests that trailing whitespaces within lines do not get stripped.
# Tests that a trailing non-terminated line does not get stripped.
quote = (
'''Agamemnon \n'''
'''\tWhy will he not upon our fair request\r\n'''
'''\tUntent his person and share the air with us?'''
)
# Make a request and monkey-patch its contents
r = get(httpbin('get'), prefetch=False)
r.raw = StringIO(quote)
lines = list(r.iter_lines())
len_lines = len(lines)
self.assertEqual(len_lines, 3)
joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]
self.assertEqual(joined, quote)
开发者ID:maxcountryman,项目名称:requests,代码行数:29,代码来源:test_requests.py
示例8: test_unicode_header_name
def test_unicode_header_name(self):
requests.put(
httpbin('put'),
headers={
str('Content-Type'): 'application/octet-stream' # compat.str is unicode.
},
data='\xff'
)
开发者ID:jtwaleson,项目名称:requests,代码行数:8,代码来源:test_requests.py
示例9: safe_unicode
def safe_unicode(obj, *args):
""" return the unicode representation of obj """
try:
return unicode(obj, *args)
except UnicodeDecodeError:
# obj is byte string
ascii_text = str(obj).encode('string_escape')
return unicode(ascii_text)
开发者ID:royburns,项目名称:pyServerAPITest,代码行数:8,代码来源:test_QiuShiBaiKe.py
示例10: test_urllib3_pool_connection_closed
def test_urllib3_pool_connection_closed(httpbin):
s = requests.Session()
s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))
try:
s.get(httpbin('status/200'))
except ConnectionError as e:
assert u"Pool is closed." in str(e)
开发者ID:503945930,项目名称:requests,代码行数:8,代码来源:test_requests.py
示例11: test_http_error
def test_http_error(self):
error = requests.exceptions.HTTPError()
self.assertEqual(error.response, None)
response = requests.Response()
error = requests.exceptions.HTTPError(response=response)
self.assertEqual(error.response, response)
error = requests.exceptions.HTTPError('message', response=response)
self.assertEqual(str(error), 'message')
self.assertEqual(error.response, response)
开发者ID:JohnPeacock,项目名称:requests,代码行数:9,代码来源:test_requests.py
示例12: test_http_error
def test_http_error(self):
error = requests.exceptions.HTTPError()
assert not error.response
response = requests.Response()
error = requests.exceptions.HTTPError(response=response)
assert error.response == response
error = requests.exceptions.HTTPError("message", response=response)
assert str(error) == "message"
assert error.response == response
开发者ID:RRedwards,项目名称:requests,代码行数:9,代码来源:test_requests.py
示例13: _get_response
def _get_response(args):
auto_json = args.data and not args.form
if args.json or auto_json:
# JSON
if 'Content-Type' not in args.headers:
args.headers['Content-Type'] = TYPE_JSON
if 'Accept' not in args.headers:
# Default Accept to JSON as well.
args.headers['Accept'] = 'application/json'
if isinstance(args.data, dict):
# If not empty, serialize the data `dict` parsed from arguments.
# Otherwise set it to `None` avoid sending "{}".
args.data = json.dumps(args.data) if args.data else None
elif args.form:
# Form
if not args.files and 'Content-Type' not in args.headers:
# If sending files, `requests` will set
# the `Content-Type` for us.
args.headers['Content-Type'] = TYPE_FORM
# Fire the request.
try:
credentials = None
if args.auth:
auth_type = (requests.auth.HTTPDigestAuth
if args.auth_type == 'digest'
else requests.auth.HTTPBasicAuth)
credentials = auth_type(args.auth.key, args.auth.value)
return requests.request(
method=args.method.lower(),
url=args.url if '://' in args.url else 'http://%s' % args.url,
headers=args.headers,
data=args.data,
verify={'yes': True, 'no': False}.get(args.verify, args.verify),
timeout=args.timeout,
auth=credentials,
proxies=dict((p.key, p.value) for p in args.proxy),
files=args.files,
allow_redirects=args.allow_redirects,
params=args.queries,
)
except (KeyboardInterrupt, SystemExit):
sys.stderr.write('\n')
sys.exit(1)
except Exception as e:
if args.traceback:
raise
sys.stderr.write(str(e.message) + '\n')
sys.exit(1)
开发者ID:codeinpeace,项目名称:httpie,代码行数:56,代码来源:__main__.py
示例14: _get_response
def _get_response(parser, args, stdin, stdin_isatty):
if not stdin_isatty:
if args.data:
parser.error('Request body (stdin) and request '
'data (key=value) cannot be mixed.')
args.data = stdin.read()
if args.json or (not args.form and args.data):
# JSON
if not args.files and (
'Content-Type' not in args.headers
and (args.data or args.json)):
args.headers['Content-Type'] = TYPE_JSON
if stdin_isatty:
# Serialize the parsed data.
args.data = json.dumps(args.data)
if 'Accept' not in args.headers:
# Default Accept to JSON as well.
args.headers['Accept'] = 'application/json'
elif not args.files and 'Content-Type' not in args.headers:
# Form
args.headers['Content-Type'] = TYPE_FORM
# Fire the request.
try:
credentials = None
if args.auth:
auth_type = (requests.auth.HTTPDigestAuth
if args.auth_type == 'digest'
else requests.auth.HTTPBasicAuth)
credentials = auth_type(args.auth.key, args.auth.value)
return requests.request(
method=args.method.lower(),
url=args.url if '://' in args.url else 'http://%s' % args.url,
headers=args.headers,
data=args.data,
verify={'yes': True, 'no': False}.get(args.verify, args.verify),
timeout=args.timeout,
auth=credentials,
proxies=dict((p.key, p.value) for p in args.proxy),
files=args.files,
allow_redirects=args.allow_redirects,
)
except (KeyboardInterrupt, SystemExit):
sys.stderr.write('\n')
sys.exit(1)
except Exception as e:
if args.traceback:
raise
sys.stderr.write(str(e.message) + '\n')
sys.exit(1)
开发者ID:AnthonyNystrom,项目名称:httpie,代码行数:54,代码来源:__main__.py
示例15: converte_dicionario_unicode_em_ascii
def converte_dicionario_unicode_em_ascii(data):
if isinstance(data, str):
try:
return str(data)
except:
return data
elif isinstance(data, collections.Mapping):
return dict(list(map(converte_dicionario_unicode_em_ascii, iter(list(data.items())))))
elif isinstance(data, collections.Iterable):
return type(data)(list(map(converte_dicionario_unicode_em_ascii, data)))
else:
return data
开发者ID:cisalhante,项目名称:matricula-o-matic,代码行数:12,代码来源:auxiliar_dados.py
示例16: headers
def headers(self):
headers = dict(self._orig.headers)
content_type = headers.get('Content-Type')
if isinstance(content_type, bytes):
# Happens when uploading files.
# TODO: submit a bug report for Requests
headers['Content-Type'] = str(content_type)
if 'Host' not in headers:
headers['Host'] = urlparse(self._orig.url).netloc
return '\n'.join('%s: %s' % (name, value)
for name, value in headers.items())
开发者ID:dai,项目名称:httpie,代码行数:14,代码来源:models.py
示例17: make_request_message
def make_request_message(request):
"""Make an `HTTPMessage` from `requests.models.Request`."""
url = urlparse(request.url)
request_headers = dict(request.headers)
if 'Host' not in request_headers:
request_headers['Host'] = url.netloc
return HTTPMessage(
line='{method} {path} HTTP/1.1'.format(
method=request.method,
path=url.path or '/'),
headers=NEW_LINE.join(str('%s: %s') % (name, value)
for name, value
in request_headers.items()),
body=request._enc_data,
content_type=request_headers.get('Content-Type')
)
开发者ID:macro,项目名称:httpie,代码行数:16,代码来源:__main__.py
示例18: main
def main(args=sys.argv[1:], env=Environment()):
"""Run the main program and write the output to ``env.stdout``.
Return exit status.
"""
if env.is_windows and not env.stdout_isatty:
env.stderr.write(
'http: error: Output redirection is not supported on Windows.'
' Please use `--output FILE\' instead.\n')
return 1
try:
args = parser.parse_args(args=args, env=env)
response = get_response(args, env)
status = 0
if args.check_status:
status = get_exist_status(response.status_code,
args.allow_redirects)
if status and not env.stdout_isatty:
err = 'http error: %s %s\n' % (
response.raw.status, response.raw.reason)
env.stderr.write(err)
try:
# We are writing bytes so we use buffer on Python 3
buffer = env.stdout.buffer
except AttributeError:
buffer = env.stdout
for chunk in output_stream(args, env, response.request, response):
buffer.write(chunk)
if env.stdout_isatty:
env.stdout.flush()
except (KeyboardInterrupt, SystemExit):
env.stderr.write('\n')
return 1
except Exception as e:
if '--debug' in args:
raise
env.stderr.write(str(repr(e) + '\n'))
return 1
return status
开发者ID:dai,项目名称:httpie,代码行数:47,代码来源:core.py
示例19: headers
def headers(self):
original = self._orig.raw._original_response
status_line = 'HTTP/{version} {status} {reason}'.format(
version='.'.join(str(original.version)),
status=original.status,
reason=original.reason
)
headers = [status_line]
try:
# `original.msg` is a `http.client.HTTPMessage` on Python 3
# `_headers` is a 2-tuple
headers.extend(
'%s: %s' % header for header in original.msg._headers)
except AttributeError:
# and a `httplib.HTTPMessage` on Python 2.x
# `headers` is a list of `name: val<CRLF>`.
headers.extend(h.strip() for h in original.msg.headers)
return '\r\n'.join(headers)
开发者ID:bkvirendra,项目名称:httpie,代码行数:19,代码来源:models.py
示例20: _parse_items
def _parse_items(self, args):
"""Parse `args.items` into `args.headers`, `args.data`,
`args.`, and `args.files`.
"""
args.headers = CaseInsensitiveDict()
args.data = ParamDict() if args.form else OrderedDict()
args.files = OrderedDict()
args.params = ParamDict()
try:
parse_items(items=args.items,
headers=args.headers,
data=args.data,
files=args.files,
params=args.params)
except ParseError as e:
if args.traceback:
raise
self.error(str(e))
if args.files and not args.form:
# `http url @/path/to/file`
file_fields = list(args.files.keys())
if file_fields != ['']:
self.error(
'Invalid file fields (perhaps you meant --form?): %s'
% ','.join(file_fields))
fn, fd = args.files['']
args.files = {}
self._body_from_file(args, fd)
if 'Content-Type' not in args.headers:
mime, encoding = mimetypes.guess_type(fn, strict=False)
if mime:
content_type = mime
if encoding:
content_type = '%s; charset=%s' % (mime, encoding)
args.headers['Content-Type'] = content_type
开发者ID:simonbuchan,项目名称:httpie,代码行数:39,代码来源:input.py
注:本文中的requests.compat.str函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论