本文整理汇总了Python中requests.PreparedRequest方法的典型用法代码示例。如果您正苦于以下问题:Python requests.PreparedRequest方法的具体用法?Python requests.PreparedRequest怎么用?Python requests.PreparedRequest使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类requests
的用法示例。
在下文中一共展示了requests.PreparedRequest方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: from_prepared_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def from_prepared_request(cls, prepared: requests.PreparedRequest) -> "Request":
"""A prepared request version is already stored in `requests.Response`."""
body = prepared.body or b""
if isinstance(body, str):
# can be a string for `application/x-www-form-urlencoded`
body = body.encode("utf-8")
# these values have `str` type at this point
uri = cast(str, prepared.url)
method = cast(str, prepared.method)
return cls(
uri=uri,
method=method,
headers={key: [value] for (key, value) in prepared.headers.items()},
body=base64.b64encode(body).decode(),
)
示例2: _normalize_requests_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def _normalize_requests_request(request):
import requests
if not isinstance(request, (requests.Request, requests.PreparedRequest)):
raise TypeError("Cannot normalize this request object")
url = request.url
method = request.method.lower()
content_type = request.headers.get('Content-Type')
body = request.body
return Request(
url=url,
body=body,
method=method,
content_type=content_type,
request=request,
headers=request.headers,
)
示例3: new_instance
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def new_instance(self, api_data: VeraApiData) -> VeraControllerData:
"""Create new instance of controller."""
base_url = "http://127.0.0.1:123"
def callback(req: requests.PreparedRequest) -> ResponsesResponse:
nonlocal api_data
return handle_request(req, api_data)
self.rsps.add_callback(
method=responses.GET,
url=re.compile(f"{base_url}/data_request?.*"),
callback=callback,
content_type="application/json",
)
controller = VeraController("http://127.0.0.1:123")
controller.data_request({"id": "sdata"})
controller.start()
# Stop the controller after the test stops and fixture is torn down.
self.pytest_req.addfinalizer(controller.stop)
return VeraControllerData(api_data=api_data, controller=controller)
示例4: _make_extra_headers
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def _make_extra_headers(self, url: str, headers: Mapping[str, Any]) -> Mapping[str, Any]:
"""
Returns the headers we should pass for this request. This includes both the AWS v4 signature
authentication ones as well as the Sec-WebSocket-* ones (which might vary and mess up the signatures used in
authentication)
"""
raw_request: bytes = self._get_raw_request_for(url=url, header=headers, **self.extra_websocket_options)
request: PreparedRequest = self._parse_raw_request(raw_request)
before_auth = set([k.lower() for k in request.headers.keys()])
# we're always supposed to exclude these but AWS4Auth will include them with include_hdrs='*', so just delete
# from the fake PreparedRequest we pass to AWS4Auth
for k in set(request.headers.keys()):
if k.lower() in ('connection', 'x-amzn-trace-id'):
del request.headers[k]
# usually mutates request (contract is to return it though, so cover our bases)
request = self.aws4auth(request)
# keep header if added by websocket client or aws4auth
extra_headers = dict()
for k, v in request.headers.items():
if k.lower() not in before_auth or k.lower().startswith('sec-websocket'):
extra_headers[k] = v
return extra_headers
示例5: build_url_with_query_params
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def build_url_with_query_params(base_url, query_params):
"""Builds a URL with GET query parameters `query_params`
"""
try:
r = requests.PreparedRequest()
r.prepare_url(base_url, query_params)
url = r.url
except requests.exceptions.MissingSchema:
# `base_url` isn't a full URL, use another placeholder just to generate the query portion
r = requests.PreparedRequest()
r.prepare_url('http://hacktoolkit.com', query_params)
temp_url = r.url
url_parts = temp_url.split('?')
query = url_parts[1] if len(url_parts) == 2 else None
url = '%s?%s' % (base_url, query,)
return url
示例6: make_url
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def make_url(self, container=None, resource=None, query_items=None):
"""Create a URL from the specified parts."""
pth = [self._base_url]
if container:
pth.append(container.strip('/'))
if resource:
pth.append(resource)
else:
pth.append('')
url = '/'.join(pth)
if isinstance(query_items, (list, tuple, set)):
url += RestHttp._list_query_str(query_items)
query_items = None
p = requests.PreparedRequest()
p.prepare_url(url, query_items)
return p.url
示例7: decode
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def decode(self, o):
"""
Decode the contents of the given JSON dictionary as an object used by Web Sight.
:param o: The JSON dictionary to process.
:return: The contents of the given JSON dictionary deserialized into an object.
"""
from lib.arin.response import BaseArinResponse
from ..geolocation import IpGeolocation
if "__class_type" not in o:
raise UnsupportedDeserializationError("No class type specified in JSON dictionary: %s" % o)
class_type = o["__class_type"]
deserialization_class = get_class_from_import_string(class_type)
if deserialization_class == PreparedRequest:
return self.__deserialize_requests_prepared_request(o)
elif deserialization_class == Response:
return self.__deserialize_requests_response(o)
elif issubclass(deserialization_class, BaseArinResponse):
return self.__deserialize_arin_response(o)
elif deserialization_class == IpGeolocation:
return self.__deserialize_ip_geolocation(o)
else:
raise UnsupportedDeserializationError(
"Class %s does not have a deserialization method."
% deserialization_class
)
示例8: encode
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def encode(self, o):
"""
Encode the contents of the given object into JSON.
:param o: The object to process.
:return: The contents of the given object in JSON format.
"""
from lib.arin.response import BaseArinResponse
from ..geolocation import IpGeolocation
if isinstance(o, PreparedRequest):
return self.__serialize_requests_prepared_request(o)
elif isinstance(o, Response):
return self.__serialize_requests_response(o)
elif isinstance(o, BaseArinResponse):
return self.__serialize_arin_response(o)
elif isinstance(o, IpGeolocation):
return self.__serialize_ip_geolocation(o)
else:
return super(WsSerializableJSONEncoder, self).encode(o)
# Protected Methods
# Private Methods
示例9: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def __init__(
self,
name: str,
title: str,
status: int,
detail: str,
response: requests.Response,
):
request: requests.PreparedRequest = response.request
super().__init__("looker-api-errors/" + name, title, detail)
self.status = status
self.looker_api_response: Optional[JsonDict] = details_from_http_error(response)
self.request = {"url": request.url, "method": request.method}
示例10: test_handle_exceptions_looker_error_should_log_response_and_status
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def test_handle_exceptions_looker_error_should_log_response_and_status(caplog):
caplog.set_level(logging.DEBUG)
response = Mock(spec=requests.Response)
response.request = Mock(spec=requests.PreparedRequest)
response.request.url = "https://api.looker.com"
response.request.method = "GET"
response.json.return_value = {
"message": "Not found",
"documentation_url": "http://docs.looker.com/",
}
status = 404
@handle_exceptions
def raise_exception():
raise LookerApiError(
name="exception-name",
title="An exception occurred.",
detail="Couldn't handle the truth. Please try again.",
status=status,
response=response,
)
with pytest.raises(SystemExit) as pytest_error:
raise_exception()
captured = "\n".join(record.msg for record in caplog.records)
assert str(status) in captured
assert '"message": "Not found"' in captured
assert '"documentation_url": "http://docs.looker.com/"' in captured
assert pytest_error.value.code == 101
示例11: mock_404_response
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def mock_404_response():
mock_request = Mock(spec=requests.PreparedRequest)
mock_request.method = "POST"
mock_request.url = "https://spectacles.looker.com"
mock_response = Mock(spec=requests.Response)
mock_response.status_code = 404
mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError(
"An HTTP error occurred."
)
mock_response.request = mock_request
return mock_response
示例12: get_prepared_request
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def get_prepared_request(data: Dict[str, Any]) -> requests.PreparedRequest:
"""Create a `requests.PreparedRequest` from a serialized one."""
prepared = requests.PreparedRequest()
prepared.method = data["method"]
prepared.url = data["uri"]
prepared._cookies = RequestsCookieJar() # type: ignore
encoded = data["body"]["base64_string"]
if encoded:
prepared.body = base64.b64decode(encoded)
# There is always 1 value in a request
headers = [(key, value[0]) for key, value in data["headers"].items()]
prepared.headers = CaseInsensitiveDict(headers)
return prepared
示例13: __init__
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def __init__(self, request: PreparedRequest, message: str):
super().__init__(message)
self.request = request
示例14: create_signature
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def create_signature(self, payload, secret):
if not isinstance(secret,bytes):
secret = secret.encode('utf-8')
if not isinstance(payload,string_types):
# Data will be forms encoded
payload = requests.PreparedRequest()._encode_params(payload)
hmac = SHA256.new(secret)
if not isinstance(payload,bytes):
payload = payload.encode('utf-8')
hmac.update(payload)
return 'sha256=' + hmac.hexdigest()
示例15: request_by_proxy
# 需要导入模块: import requests [as 别名]
# 或者: from requests import PreparedRequest [as 别名]
def request_by_proxy(self, method, url, timeout=None, **kwargs) -> requests.Response:
if not self.has_rss_proxy:
raise ValueError("rss_proxy_url not provided")
if timeout is None:
timeout = _DEFAULT_TIMEOUT
request: requests.PreparedRequest
request = requests.Request(method, url, **kwargs).prepare()
request_body = None
if request.body:
if isinstance(request.body, bytes):
request_body = request.body.decode('utf-8')
elif isinstance(request.body, str):
request_body = request.body
else:
msg = f'not support request body type {type(request.body).__name__}'
raise ValueError(msg)
headers = dict(request.headers)
headers['user-agent'] = _DEFAULT_USER_AGENT
proxy_data = {
'method': request.method,
'token': self.rss_proxy_token,
'url': request.url,
'headers': headers,
'body': request_body,
}
response = requests.post(self.rss_proxy_url, json=proxy_data, timeout=timeout)
response.close()
proxy_status = response.headers.get('x-rss-proxy-status', None)
if response.status_code != 200 or proxy_status == 'ERROR':
msg = 'status={} {}'.format(response.status_code, response.text)
raise RSSProxyClientError(msg)
response.status_code = int(proxy_status)
return response