Here are the examples of the python api requests.models.Response taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
122 Examples
5
Source : zenodo_upload.py
with Apache License 2.0
from espnet
with Apache License 2.0
from espnet
def update_metadata(
self, r: Union[requests.models.Response, int], data
) -> requests.models.Response:
if isinstance(r, requests.models.Response):
deposition_id = r.json()["id"]
else:
deposition_id = r
r = requests.put(
f"{self.zenodo_url}/api/deposit/depositions/{deposition_id}",
params=self.params,
data=json.dumps(data),
headers=self.headers,
)
if r.status_code != 200:
raise RuntimeError(r.json()["message"])
return r
def upload_file(
5
Source : zenodo_upload.py
with Apache License 2.0
from espnet
with Apache License 2.0
from espnet
def publish(
self, r: Union[requests.models.Response, int]
) -> requests.models.Response:
if isinstance(r, requests.models.Response):
deposition_id = r.json()["id"]
else:
deposition_id = r
r = requests.post(
f"{self.zenodo_url}/api/deposit/depositions/"
f"{deposition_id}/actions/publish",
params=self.params,
)
if r.status_code != 202:
raise RuntimeError(r.json()["message"])
return r
def upload(
5
Source : dropbox_client.py
with MIT License
from osamhack2021
with MIT License
from osamhack2021
def __init__(self, obj_result, http_resp=None):
"""
:param str obj_result: The result of a route not including the binary
payload portion, if one exists. Must be serialized JSON.
:param requests.models.Response http_resp: A raw HTTP response. It will
be used to stream the binary-body payload of the response.
"""
assert isinstance(obj_result, six.string_types), \
'obj_result: expected string, got %r' % type(obj_result)
if http_resp is not None:
assert isinstance(http_resp, requests.models.Response), \
'http_resp: expected requests.models.Response, got %r' % \
type(http_resp)
self.obj_result = obj_result
self.http_resp = http_resp
class RouteErrorResult(object):
3
Source : decorator.py
with Apache License 2.0
from airbnb
with Apache License 2.0
from airbnb
def __call__(self, func):
def wrapper(*args):
try:
response: requests.models.Response = func(*args)
LOGGER.info(response.content)
except Exception:
LOGGER.error(self.message)
raise ValueError
return wrapper
# HTTP Request Error Handling
def http_exception(func):
3
Source : decorator.py
with Apache License 2.0
from airbnb
with Apache License 2.0
from airbnb
def http_exception(func):
def wrapper(*args, **kwargs):
resp: requests.models.Response = func(*args, **kwargs)
if resp.status_code >= 400:
LOGGER.error(**json.loads(resp._content))
sys.exit(1)
else:
return resp
return wrapper
3
Source : IS1001Test.py
with Apache License 2.0
from AMWA-TV
with Apache License 2.0
from AMWA-TV
def _verify_response(self, test, expected_status, response):
"""Verify if HTTP response status code is valid"""
if isinstance(response, requests.models.Response):
try:
response.raise_for_status()
except Exception:
self._raise_nmos_exception(test, response)
elif isinstance(response, str):
raise NMOSTestException(test.FAIL(
"Request to Auth Server failed due to: {}".format(response)))
if response.status_code != expected_status:
self._raise_nmos_exception(test, response, "Expected status_code: {}".format(expected_status))
def _verify_redirect(self, test, response, input_params, query_key, expected_query_value=None):
3
Source : test_vault.py
with Mozilla Public License 2.0
from bincyber
with Mozilla Public License 2.0
from bincyber
def setUp(self):
self.baseurl = "https://localhost:8200"
self.vault_client = VaultClient(baseurl=self.baseurl)
self.test_response = Response()
self.vault_client.request = MagicMock(return_value=self.test_response)
def test_vault_header(self):
3
Source : bluecat.py
with Apache License 2.0
from bluecatlabs
with Apache License 2.0
from bluecatlabs
def generate_mocked_response(self, resource, action):
""" Create mock response object.
Used for mocking responses to actions that can modify a resource when running in Ansible's `check mode`.
:param resource: The name of the resource that the action should be performed on.
:param action: The REST verb that needs to be performed on the resource.
:return: A mocked Response object.
"""
response = requests.models.Response()
response.status_code = self.response_key[action.upper()]
response._content = {'message': 'No changes made to {resource}'.format(resource=resource)}
return response
def parse_query_params(self, definition):
3
Source : test_client.py
with MIT License
from cruxinformatics
with MIT License
from cruxinformatics
def monkeypatch_delete_call(
self,
method=None,
url=None,
headers=None,
params=None,
json=None,
data=None,
stream=False,
proxies=None,
timeout=None,
):
delete_resp = Response()
delete_resp.status_code = 204
return delete_resp
def test_client_delete(client, monkeypatch):
3
Source : test_client.py
with MIT License
from cruxinformatics
with MIT License
from cruxinformatics
def monkeypatch_get_call_with_no_model(
self,
method=None,
url=None,
headers=None,
params=None,
json=None,
data=None,
stream=False,
proxies=None,
timeout=None,
):
get_resp = Response()
get_resp.status_code = 200
get_resp._content = b'{"data":"dummy"}'
return get_resp
def test_client_get_with_no_model(client, monkeypatch):
3
Source : test_client.py
with MIT License
from cruxinformatics
with MIT License
from cruxinformatics
def monkeypatch_get_call(
self,
method=None,
url=None,
headers=None,
params=None,
json=None,
data=None,
stream=False,
proxies=None,
timeout=None,
):
get_resp = Response()
get_resp.status_code = 200
get_resp._content = b'{"attr1":"dummy1","attr2":"dummy2"}'
return get_resp
def test_client_get_with_model(client, monkeypatch):
3
Source : test_client.py
with MIT License
from cruxinformatics
with MIT License
from cruxinformatics
def monkeypatch_post_call(
self,
method=None,
url=None,
headers=None,
stream=False,
params=None,
data=None,
json=None,
proxies=None,
timeout=None,
):
get_resp = Response()
get_resp.status_code = 200
get_resp._content = b'{"attr1":"dummy1","attr2":"dummy2"}'
return get_resp
def test_client_post(client, monkeypatch):
3
Source : test_client.py
with MIT License
from cruxinformatics
with MIT License
from cruxinformatics
def monkeypatch_put_call(
self,
method=None,
url=None,
headers=None,
stream=False,
json=None,
params=None,
data=None,
proxies=None,
timeout=None,
):
get_resp = Response()
get_resp.status_code = 200
get_resp._content = b'{"attr1":"dummy1","attr2":"dummy2"}'
return get_resp
def test_client_put(client, monkeypatch):
3
Source : test_client.py
with MIT License
from cruxinformatics
with MIT License
from cruxinformatics
def monkeypatch_client_http_exception(
self,
method=None,
url=None,
headers=None,
params=None,
data=None,
json=None,
stream=False,
proxies=None,
timeout=None,
):
response = Response()
response.status_code = 404
raise HTTPError("Test HTTP Error", response=response)
def test_client_http_exception(client, monkeypatch):
3
Source : test_api_requests.py
with Mozilla Public License 2.0
from cvarelaruiz
with Mozilla Public License 2.0
from cvarelaruiz
def test_getBouquets_error_endpoint(mock_get, openwebif_server):
mock_response = Response()
mock_response.status_code = 404
mock_get.return_value = mock_response
with pytest.raises(JSONDecodeError):
_ = getBouquets('-', openwebif_server, False)
3
Source : client.py
with MIT License
from dtkav
with MIT License
from dtkav
def make_response(content_id, data):
header, content = data.split(b"\r\n\r\n", 1)
response = Response()
response._content, _ = content.rsplit(b'\r\n', 1)
status, headers = header.split(b'\r\n', 1)
_, code, reason = status.split(b' ', 2)
response.code = reason
response.error_type = reason
response.status_code = int(code)
response.content_id = content_id
return response
def decode_batch_response(resp):
3
Source : test_client.py
with Apache License 2.0
from elixir-cloud-aai
with Apache License 2.0
from elixir-cloud-aai
def test_zip_io_error(self, monkeypatch, requests_mock, tmpdir):
"""Test I/O error."""
outfile = tmpdir / 'test.zip'
requests_mock.get(self.endpoint)
monkeypatch.setattr(
'builtins.open',
lambda *args, **kwargs: _raise(IOError)
)
r = self.cli.get_files(
type=MOCK_DESCRIPTOR,
id=MOCK_TRS_URI_VERSIONED,
format='zip',
outfile=outfile,
)
assert isinstance(r, requests.models.Response)
def test_zip_connection_error(self, monkeypatch, tmpdir):
3
Source : zenodo_upload.py
with Apache License 2.0
from espnet
with Apache License 2.0
from espnet
def get_deposition(self, r: Union[requests.models.Response, int]):
if isinstance(r, requests.models.Response):
deposition_id = r.json()["id"]
else:
deposition_id = r
r = requests.get(
f"{self.zenodo_url}/api/deposit/depositions/{deposition_id}",
params=self.params,
json={},
headers=self.headers,
)
if r.status_code != 200:
raise RuntimeError(r.json()["message"])
return r
def update_metadata(
3
Source : testing_utils.py
with Apache License 2.0
from exonum
with Apache License 2.0
from exonum
def proto_sources_response(service):
from requests.models import Response
with open("tests/api_responses/proto_sources_{}.json".format(service)) as file:
content = file.read()
response = Response()
response.code = "OK"
response.status_code = 200
response.headers = {"content-type": "application/json; charset=utf8"}
response._content = bytes(content, "utf-8")
return response
def mock_response(status_code, content=None):
3
Source : testing_utils.py
with Apache License 2.0
from exonum
with Apache License 2.0
from exonum
def mock_response(status_code, content=None):
import json
from requests.models import Response
from requests.status_codes import _codes as status_codes
response = Response()
response.code = status_codes[status_code][0]
response.status_code = status_code
if content:
response.headers = {"content-type": "application/json; charset=utf8"}
content = json.dumps(content)
response._content = bytes(content, "utf-8")
return response
def mock_requests_get(cls_obj, url, params=None):
3
Source : cli_utils.py
with Apache License 2.0
from FederatedAI
with Apache License 2.0
from FederatedAI
def prettify(response, verbose=True):
if verbose:
if isinstance(response, requests.models.Response):
try:
response_dict = response.json()
except TypeError:
response_dict = response.json
else:
response_dict = response
try:
click.echo(json.dumps(response_dict, indent=4, ensure_ascii=False))
except TypeError:
click.echo(json.dumps(response_dict.json, indent=4, ensure_ascii=False))
click.echo('')
return response
def access_server(method, ctx, postfix, json_data=None, echo=True, **kwargs):
3
Source : base.py
with Apache License 2.0
from FederatedAI
with Apache License 2.0
from FederatedAI
def _handle_result(self, response):
try:
if isinstance(response, requests.models.Response):
return response.json()
elif isinstance(response, dict):
return response
else:
return self._decode_result(response)
except json.decoder.JSONDecodeError:
res = {'retcode': 100,
'retmsg': "Internal server error. Nothing in response. You may check out the configuration in "
"'FATE/conf/service_conf.yaml' and restart fate flow server."}
return res
def get(self, url, **kwargs):
3
Source : utils.py
with MIT License
from gnosis
with MIT License
from gnosis
def send(self, request, **kwargs):
request._extra_kwargs = kwargs
self._recorder.append(request)
resp = models.Response()
resp.url = request.url
resp.status_code = self._status
resp.raw = self._data.encode()
return resp
def send_message(*args, message_instance, data, token):
3
Source : test_extractor.py
with MIT License
from HumanCellAtlas
with MIT License
from HumanCellAtlas
def get(self, url, params):
if "files" in url:
payload = {}
else:
payload = {"bundle": {"files": files}}
res = Response()
res.status_code = self.status_code
res.raw = io.BytesIO(json.dumps(payload).encode())
return res
class MockDSSClient(MockHTTPClient):
3
Source : exceptions.py
with MIT License
from ianjwhite99
with MIT License
from ianjwhite99
def __init__(self, response):
self.message = 'Unknown error'
if isinstance(response, requests.models.Response):
json = response.json()
if 'message' in json:
self.message = json['message']
elif 'error_description' in json:
self.message = json['error_description']
elif isinstance(response, str):
self.message = response
def __str__(self):
3
Source : common.py
with MIT License
from jeffzh3ng
with MIT License
from jeffzh3ng
def http_request_get(url, body_content_workflow=False, allow_redirects=allow_redirects, custom_cookie=""):
try:
if custom_cookie:
headers['Cookie']=custom_cookie
result = requests.get(url,
stream=body_content_workflow,
headers=headers,
timeout=timeout,
proxies=proxies,
allow_redirects=allow_redirects,
verify=allow_ssl_verify)
return result
except Exception as e:
# return empty requests object
return __requests__.models.Response()
def http_request_post(url, payload, body_content_workflow=False, allow_redirects=allow_redirects, custom_cookie=""):
3
Source : common.py
with MIT License
from jeffzh3ng
with MIT License
from jeffzh3ng
def http_request_post(url, payload, body_content_workflow=False, allow_redirects=allow_redirects, custom_cookie=""):
""" payload = {'key1': 'value1', 'key2': 'value2'} """
try:
if custom_cookie:
headers['Cookie']=custom_cookie
result = requests.post(url,
data=payload,
headers=headers,
stream=body_content_workflow,
timeout=timeout,
proxies=proxies,
allow_redirects=allow_redirects,
verify=allow_ssl_verify)
return result
except Exception as e:
# return empty requests object
return __requests__.models.Response()
def curl_get_content(url):
3
Source : helper.py
with MIT License
from jmfernandes
with MIT License
from jmfernandes
def get_order_number(data):
""" Gets the
"""
try:
if type(data) is requests.models.Response:
parse_string = data.headers["Location"]
elif type(data) is dict or type(data) is requests.structures.CaseInsensitiveDict:
parse_string = data["Location"]
else:
parse_string = data
except Exception as e:
raise ValueError("{0} is not a value in the dictionary".format(e))
_, order_id = split("orders/", parse_string, IGNORECASE)
return(order_id)
def format_inputs(func):
3
Source : TypeTool.py
with MIT License
from LianjiaTech
with MIT License
from LianjiaTech
def is_requests_Response(objData):
if type(requests.models.Response()) == type(objData):
return True
else:
return False
@staticmethod
3
Source : test_helper.py
with MIT License
from miurahr
with MIT License
from miurahr
def mocked_requests_get(*args, **kwargs):
response = Response()
response.status_code = 200
response.iter_content = mocked_iter_content
return response
def test_helper_downloadBinary_md5(tmp_path, monkeypatch):
3
Source : test_download.py
with BSD 3-Clause "New" or "Revised" License
from nokia
with BSD 3-Clause "New" or "Revised" License
from nokia
def test_download():
success = 0
for url in URLS:
response = download(url)
if isinstance(response, requests.models.Response):
success += 1
assert success >= 1
def test_download_connector():
3
Source : _utils.py
with MIT License
from osamhack2021
with MIT License
from osamhack2021
def _http_response_from_googleapiclient_error(error):
"""Creates a requests HTTP Response object from the given googleapiclient error."""
resp = requests.models.Response()
resp.raw = io.BytesIO(error.content)
resp.status_code = error.resp.status
return resp
def _http_status_to_error_code(status):
3
Source : WebRequest.py
with MIT License
from ozhiwei
with MIT License
from ozhiwei
def get(self, url, header=None, retry_time=1, timeout=10,
*args, **kwargs):
headers = self.header
if header and isinstance(header, dict):
headers.update(header)
try:
resp = requests.get(url, headers=headers, timeout=timeout, **kwargs)
except Exception as e:
# print("request url error", url, e)
resp = Response()
resp.status_code = 504
return resp
3
Source : base.py
with Apache License 2.0
from ProzorroUKR
with Apache License 2.0
from ProzorroUKR
def bad_rs_request(method, url, **kwargs):
response = Response()
response.status_code = 403
response.encoding = "application/json"
response._content = '"Unauthorized: upload_view failed permission check"'
response.reason = "403 Forbidden"
return response
srequest = SESSION.request
3
Source : decorators.py
with Apache License 2.0
from PYART0
with Apache License 2.0
from PYART0
def generate_fake_error_response(msg, status_code=401, encoding='utf-8'):
r = Response()
r.status_code = status_code
r.encoding = encoding
r.raw = RequestsStringIO(msg.encode())
r._content_consumed = True
r._content = r.raw.read()
return r
# Use mock decorators when generating documentation, so all functino signatures
# are displayed correctly
if os.getenv('GENERATING_DOCUMENTATION', None) == 'github3':
3
Source : test_pypi_repository.py
with MIT License
from python-poetry
with MIT License
from python-poetry
def test_get_should_invalid_cache_on_too_many_redirects_error(mocker: MockerFixture):
delete_cache = mocker.patch("cachecontrol.caches.file_cache.FileCache.delete")
response = Response()
response.encoding = "utf-8"
response.raw = BytesIO(encode('{"foo": "bar"}'))
mocker.patch(
"cachecontrol.adapter.CacheControlAdapter.send",
side_effect=[TooManyRedirects(), response],
)
repository = PyPiRepository()
repository._get("https://pypi.org/pypi/async-timeout/json")
assert delete_cache.called
def test_urls():
3
Source : test_requests.py
with MIT License
from RamParameswaran
with MIT License
from RamParameswaran
def mock_python_get_request(self, monkeypatch):
resp = python_requests.models.Response()
resp.status_code = 200
resp._content = b" < html>Hello test! < /html>"
monkeypatch.setattr(python_requests, "get", mock.Mock())
python_requests.get.return_value = resp
def test_none_url_throws_exception(self):
3
Source : test_wso.py
with Apache License 2.0
from rorymurdock
with Apache License 2.0
from rorymurdock
def test_expected():
"""Test HTTP expected response"""
response = requests.models.Response()
response.status_code = 200
assert UEM.check_http_response(response, 200) is True
def test_unexpected():
3
Source : test_wso.py
with Apache License 2.0
from rorymurdock
with Apache License 2.0
from rorymurdock
def test_unexpected():
"""Tests unexpected response is returns as False"""
response = requests.models.Response()
response.status_code = 'unexpected'
assert UEM.check_http_response(response) is False
def test_true_http():
3
Source : tools.py
with MIT License
from rubrikinc
with MIT License
from rubrikinc
def jsonfy(self, avar):
"""Load json data from string."""
avar_dict = {}
if isinstance(avar, requests.models.Response):
avar_dict = self.json_load(avar.text)
elif isinstance(avar, dict) or isinstance(avar, list):
avar_dict = avar
else:
avar_dict['result'] = str(avar)
return self.json_dump(avar_dict)
def cp_dict(self, existing_dict):
3
Source : downloader_test.py
with MIT License
from Senth
with MIT License
from Senth
def test_get_when_non_strict_json(downloader):
response = Response()
response.encoding = "UTF-8"
response.status_code = 200
response._content = '\n{"text":"This is\nmy text"}'.encode("UTF-8")
expected = {"text": "This is\nmy text"}
when(requests).get(...).thenReturn(response)
result = downloader.get("https://test.com")
assert expected == result
unstub()
def test_download_failed(downloader, mock_response):
3
Source : test_discovery_mode.py
with GNU Affero General Public License v3.0
from singer-io
with GNU Affero General Public License v3.0
from singer-io
def mocked_get(*args, **kwargs):
fake_response = requests.models.Response()
fake_response.headers.update(kwargs.get('headers', {}))
fake_response.status_code = kwargs['status_code']
# We can't set the content or text of the Response directly, so we mock a function
fake_response.json = Mock()
fake_response.json.side_effect = lambda:kwargs.get('json', {})
return fake_response
class TestDiscovery(unittest.TestCase):
3
Source : test_http.py
with GNU Affero General Public License v3.0
from singer-io
with GNU Affero General Public License v3.0
from singer-io
def mocked_get(*args, **kwargs):
fake_response = requests.models.Response()
fake_response.headers.update(kwargs.get('headers', {}))
fake_response.status_code = kwargs['status_code']
# We can't set the content or text of the Response directly, so we mock a function
fake_response.json = Mock()
fake_response.json.side_effect = lambda:kwargs.get('json', {})
return fake_response
@patch("time.sleep")
3
Source : test_http.py
with GNU Affero General Public License v3.0
from singer-io
with GNU Affero General Public License v3.0
from singer-io
def test_get_cursor_based_handles_444(self,mock_get, mock_sleep):
fake_response = requests.models.Response()
fake_response.status_code = 444
mock_get.side_effect = [fake_response]
try:
responses = [response for response in http.get_cursor_based(url='some_url',
access_token='some_token', request_timeout=300)]
except http.ZendeskError as e:
expected_error_message = 'HTTP-error-code: 444, Error: Unknown Error'
# Verify the message formed for the custom exception
self.assertEqual(str(e), expected_error_message)
self.assertEqual(mock_get.call_count, 1)
@patch("tap_zendesk.streams.LOGGER.warning")
3
Source : decorator.py
with MIT License
from stytchauth
with MIT License
from stytchauth
def throw_stytch_exception(func):
def wrapper(*args, **kwargs):
resp: requests.models.Response = func(*args, **kwargs)
if resp.status_code >= 400:
raise StytchError(**json.loads(resp._content))
else:
return resp
return wrapper
3
Source : fixtures.py
with MIT License
from trevorphillipscoding
with MIT License
from trevorphillipscoding
def get_success_response():
mock = requests.models.Response()
mock.status_code = 200
mock._content = b"{}"
return mock
@pytest.fixture
3
Source : test_pywnedpasswords.py
with MIT License
from xmatthias
with MIT License
from xmatthias
def mock_response():
"""Mock response for Passw0rd!"""
the_response = Response()
the_response.status_code = 200
the_response._content = b"""973E7B0BF9D160F9F60E3C3ACD2494BEB0D: 1286
943B1609FFFBFC51AAD666D0A04ADF83C9D:1234"""
return the_response
def test_hashpass():
2
Source : web.py
with MIT License
from herrmannlab
with MIT License
from herrmannlab
def _http_get(
self,
url: str,
params: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
stream: bool = False
) -> requests.models.Response:
"""Perform an HTTP GET request.
Parameters
----------
url: str
Unique resource locator
params: Union[Dict[str, Any], None], optional
Query parameters
headers: Union[Dict[str, str], None], optional
Request message headers
stream: bool, optional
Whether data should be streamed (i.e., requested using chunked
transfer encoding)
Returns
-------
requests.models.Response
Response message
"""
@retrying.retry(
retry_on_result=self._is_retriable_http_error,
wait_exponential_multiplier=self._wait_exponential_multiplier,
stop_max_attempt_number=self._max_attempts
)
def _invoke_get_request(
url: str,
headers: Optional[Dict[str, str]] = None
) -> requests.models.Response:
logger.debug(f'GET: {url} {headers}')
# Setting stream allows for retrieval of data using chunked transer
# encoding. The iter_content() method can be used to iterate over
# chunks. If stream is not set, iter_content() will return the
# full payload at once.
return self._session.get(url=url, headers=headers, stream=stream)
if headers is None:
headers = {}
if not stream:
headers['Host'] = self.host
if params is None:
params = {}
url += self._build_query_string(params)
if stream:
logger.debug('use chunked transfer encoding')
response = _invoke_get_request(url, headers)
logger.debug(f'request status code: {response.status_code}')
response.raise_for_status()
if response.status_code == 204:
logger.warning('empty response')
# The server may not return all results, but rather include a warning
# header to notify that client that there are remaining results.
# (see DICOM Part 3.18 Section 6.7.1.2)
if 'Warning' in response.headers:
logger.warning(response.headers['Warning'])
return response
def _http_get_application_json(
2
Source : web.py
with MIT License
from herrmannlab
with MIT License
from herrmannlab
def _http_post(
self,
url: str,
data: bytes,
headers: Dict[str, str]
) -> requests.models.Response:
"""Perform a HTTP POST request.
Parameters
----------
url: str
unique resource locator
data: bytes
HTTP request message payload
headers: Dict[str, str]
HTTP request message headers
Returns
-------
requests.models.Response
HTTP response message
"""
def serve_data_chunks(data):
for i, offset in enumerate(range(0, len(data), self._chunk_size)):
logger.debug(f'serve data chunk #{i}')
end = offset + self._chunk_size
yield data[offset:end]
@retrying.retry(
retry_on_result=self._is_retriable_http_error,
wait_exponential_multiplier=self._wait_exponential_multiplier,
stop_max_attempt_number=self._max_attempts
)
def _invoke_post_request(
url: str,
data: bytes,
headers: Optional[Dict[str, str]] = None
) -> requests.models.Response:
logger.debug(f'POST: {url} {headers}')
return self._session.post(url, data=data, headers=headers)
if len(data) > self._chunk_size:
logger.info('store data in chunks using chunked transfer encoding')
chunked_headers = dict(headers)
chunked_headers['Transfer-Encoding'] = 'chunked'
chunked_headers['Cache-Control'] = 'no-cache'
chunked_headers['Connection'] = 'Keep-Alive'
data_chunks = serve_data_chunks(data)
response = _invoke_post_request(url, data_chunks, chunked_headers)
else:
# There is a bug in the requests library that sets the Host header
# again when using chunked transer encoding. Apparently this is
# tricky to fix (see https://github.com/psf/requests/issues/4392).
# As a temporary workaround we are only setting the header field,
# if we don't use chunked transfer encoding.
headers['Host'] = self.host
response = _invoke_post_request(url, data, headers)
logger.debug(f'request status code: {response.status_code}')
response.raise_for_status()
if not response.ok:
logger.warning('storage was not successful for all instances')
payload = response.content
content_type = response.headers['Content-Type']
if content_type in ('application/dicom+json', 'application/json', ):
dataset = pydicom.dataset.Dataset.from_json(payload)
elif content_type in ('application/dicom+xml', 'application/xml', ):
tree = fromstring(payload)
dataset = _load_xml_dataset(tree)
else:
raise ValueError('Response message has unexpected media type.')
failed_sop_sequence = getattr(dataset, 'FailedSOPSequence', [])
for failed_sop_item in failed_sop_sequence:
logger.error(
'storage of instance {} failed: "{}"'.format(
failed_sop_item.ReferencedSOPInstanceUID,
failed_sop_item.FailureReason
)
)
return response
def _http_post_multipart_application_dicom(
2
Source : api.py
with Mozilla Public License 2.0
from marph91
with Mozilla Public License 2.0
from marph91
def _request(
self,
method: str,
path: str,
query: Optional[JoplinKwargs] = None,
data: Optional[JoplinKwargs] = None,
files: Optional[Dict[str, Any]] = None,
) -> requests.models.Response:
logging.debug(
f"API: {method} request: path={path}, query={query}, data={data}, "
f"files={files}"
)
if data is not None and "id_" in data:
# "id" is a reserved keyword in python, so don't use it.
data["id"] = data["id_"]
if query is None:
query = {}
query["token"] = self.token # TODO: extending the dict may have side effects
query_str = "&".join([f"{key}={val}" for key, val in query.items()])
try:
response: requests.models.Response = getattr(requests, method)(
f"{self.url}{path}?{query_str}",
json=data,
files=files,
)
logging.debug(f"API: response {response.text}")
response.raise_for_status()
except requests.exceptions.HTTPError as err:
err.args = err.args + (response.text,)
raise
return response
def delete(self, path: str) -> requests.models.Response:
See More Examples