Exemple #1
0
    def test_endpoints_when_multiple_endpoints(self, service):
        foo = Endpoint(path="/foo")
        bar = Endpoint(path="/bar")

        service.foo = foo
        service.bar = bar

        assert service.endpoints == {foo, bar}
Exemple #2
0
class OrthancPatients(Service):

    patients = JsonEndpoint(path="patients/")
    patient = JsonEndpoint(path="patients/{id_}/")
    del_patient = JsonEndpoint(path="patients/{id_}/", default_method="DELETE")
    anonymize = JsonEndpoint(path="patients/{id_}/anonymize/",
                             default_method="POST")
    archive = StreamingEndpoint(path="patients/{id_}/archive/")
    attachments = JsonEndpoint(path="patients/{id_}/attachments")
    attachment = JsonEndpoint(path="patients/{id_}/attachment/{name}/")
    del_attachment = JsonEndpoint(path="patients/{id_}/attachment/{name}/",
                                  default_method="DELETE")
    put_attachment = JsonEndpoint(path="patients/{id_}/attachment/{name}/",
                                  default_method="PUT")
    compress_attachment = JsonEndpoint(
        path="patients/{id_}/attachment/{name}/compress",
        default_method="POST")
    compressed_attachment_data = StreamingEndpoint(
        path="patients/{id_}/attachment/{name}/compressed-data")
    compressed_attachment_md5 = JsonEndpoint(
        path="patients/{id_}/attachment/{name}/compressed-md5")
    compressed_attachment_size = JsonEndpoint(
        path="patients/{id_}/attachment/{name}/compressed-size")
    attachment_data = StreamingEndpoint(
        path="patients/{id_}/attachment/{name}/data")
    attachment_is_compressed = JsonEndpoint(
        path="patients/{id_}/attachment/{name}/is-compressed")
    attachment_md5 = JsonEndpoint(path="patients/{id_}/attachment/{name}/md5")
    attachment_size = JsonEndpoint(
        path="patients/{id_}/attachment/{name}/size")
    uncompress_attachment = JsonEndpoint(
        path="patients/{id_}/attachment/{name}/uncompress",
        default_method="POST")
    verify_attachment = JsonEndpoint(
        path="patients/{id_}/attachment/{name}/verify-md5",
        default_method="POST")
    instances = JsonEndpoint(path="patients/{id_}/instances/")
    instances_tags = JsonEndpoint(path="patients/{id_}/instances-tags/")
    list_metadata = JsonEndpoint(path="patients/{id_}/metadata/")
    metadata = Endpoint(path="patients/{id_}/metadata/{name}/")
    del_metadata = JsonEndpoint(path="patients/{id_}/metadata/{name}/",
                                default_method="DELETE")
    put_metadata = JsonEndpoint(path="patients/{id_}/metadata/{name}/",
                                default_method="PUT")
    modify = JsonEndpoint(path="patients/{id_}/modify/", default_method="POST")
    module = JsonEndpoint(path="patients/{id_}/module/")
    media = StreamingEndpoint(path="patients/{id_}/media/")
    protected = Endpoint(path="patients/{id_}/protected/")
    put_protected = Endpoint(path="patients/{id_}/protected/",
                             default_method="PUT")
    reconstruct = JsonEndpoint(path="patients/{id_}/reconstruct/",
                               default_method="POST")
    series = JsonEndpoint(path="patients/{id_}/series/")
    shared_tags = JsonEndpoint(path="patients/{id_}/shared-tags/")
    statistics = JsonEndpoint(path="patients/{id_}/statistics/")
    studies = JsonEndpoint(path="patients/{id_}/studies/")
class ShiftCodeService(Service):
    domain = 'https://shift.gearboxsoftware.com'

    home = Endpoint(path='/home')

    login = Endpoint(path='/sessions', default_method='POST')

    check_code = Endpoint(path='/entitlement_offer_codes',
                          required_params={'code'})

    redeem_code = Endpoint(path='/code_redemptions', default_method='POST')
Exemple #4
0
def _build_request_object(
    session: requests.Session,
    service: apiron.Service,
    endpoint: apiron.Endpoint,
    method: Optional[str] = None,
    params: Optional[Dict[str, Any]] = None,
    data: Optional[Dict[str, Any]] = None,
    files: Optional[Dict[str, str]] = None,
    json: Optional[Dict[str, Any]] = None,
    headers: Optional[Dict[str, Any]] = None,
    cookies: Optional[Dict[str, Any]] = None,
    auth: Optional[Any] = None,
    **kwargs,
):
    host = _choose_host(service=service)

    path = endpoint.get_formatted_path(**kwargs)

    merged_params = endpoint.get_merged_params(params)

    headers = headers or {}
    headers.update(_get_required_headers(service, endpoint))

    request = requests.Request(
        method=method or endpoint.default_method,
        url=_build_url(host, path),
        params=merged_params,
        data=data,
        files=files,
        json=json,
        headers=headers,
        cookies=cookies,
        auth=auth,
    )

    return session.prepare_request(request)
Exemple #5
0
class OrthancInstances(Service):

    instances = JsonEndpoint(path="instances/")
    add_instance = JsonEndpoint(path="instances/", default_method="POST")
    instance = JsonEndpoint(path="instances/{id_}/")
    del_instance = JsonEndpoint(path="instances/{id_}/",
                                default_method="DELETE")
    anonymize = StreamingEndpoint(path="instances/{id_}/anonymize/",
                                  default_method="POST")
    attachments = JsonEndpoint(path="instances/{id_}/attachments")
    attachment = JsonEndpoint(path="instances/{id_}/attachment/{name}/")
    del_attachment = JsonEndpoint(path="instances/{id_}/attachment/{name}/",
                                  default_method="DELETE")
    put_attachment = JsonEndpoint(path="instances/{id_}/attachment/{name}/",
                                  default_method="PUT")
    compress_attachment = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/compress",
        default_method="POST")
    compressed_attachment_data = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/compressed-data")
    compressed_attachment_md5 = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/compressed-md5")
    compressed_attachment_size = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/compressed-size")
    attachment_data = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/data")
    attachment_is_compressed = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/is-compressed")
    attachment_md5 = JsonEndpoint(path="instances/{id_}/attachment/{name}/md5")
    attachment_size = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/size")
    uncompress_attachment = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/uncompress",
        default_method="POST")
    verify_attachment = JsonEndpoint(
        path="instances/{id_}/attachment/{name}/verify-md5",
        default_method="POST")
    content = JsonEndpoint(path="instances/{id_}/content")
    content_tag = JsonEndpoint(path="instances/{id_}/content/{tag}")
    content_raw_tag = Endpoint(
        path="instances/{id_}/content/{group}-{element}/")
    # instance_content_raw_seq = JsonEndpoint(path='instances/{id_}/content/{group}-{element}/{index}/')
    export = JsonEndpoint(path="instances/{id_}/export/",
                          default_method="POST")
    file_ = StreamingEndpoint(path="instances/{id_}/file/")
    frames = JsonEndpoint(path="instances/{id_}/frames/")
    frame = StreamingEndpoint(
        path="instances/{id_}/frames/{number}/{format_}/")
    frame_preview = StreamingEndpoint(
        path="instances/{id_}/frames/{number}/preview/")
    header = JsonEndpoint(path="instances/{id_}/header/")
    image = StreamingEndpoint(path="instances/{id_}/{format_}/")
    list_metadata = JsonEndpoint(path="instances/{id_}/metadata/")
    metadata = JsonEndpoint(path="instances/{id_}/metadata/{name}/")
    del_metadata = JsonEndpoint(path="instances/{id_}/metadata/{name}/",
                                default_method="DELETE")
    put_metadata = JsonEndpoint(path="instances/{id_}/metadata/{name}/",
                                default_method="PUT")
    modify = JsonEndpoint(path="instances/{id_}/modify/",
                          default_method="POST")
    module = JsonEndpoint(path="instances/{id_}/module/")
    patient = JsonEndpoint(path="instances/{id_}/patient/")
    pdf = StreamingEndpoint(path="instances/{id_}/pdf/")
    preview = StreamingEndpoint(path="instances/{id_}/preview/")
    reconstruct = JsonEndpoint(path="instances/{id_}/reconstruct/",
                               default_method="POST")
    series = JsonEndpoint(path="instances/{id_}/series/")
    simplified_tags = JsonEndpoint(path="instances/{id_}/simplified-tags/")
    statistics = JsonEndpoint(path="instances/{id_}/statistics/")
    study = JsonEndpoint(path="instances/{id_}/study/")
    tags = JsonEndpoint(path="instances/{id_}/tags/")
Exemple #6
0
class OrthancServer(Service):
    """Server-related endpoints"""

    changes = JsonEndpoint(path="changes/")
    del_changes = JsonEndpoint(path="changes/", default_method="DELETE")
    exports = JsonEndpoint(path="exports/")
    del_exports = JsonEndpoint(path="exports/", default_method="DELETE")

    jobs = JsonEndpoint(path="jobs/")
    job = JsonEndpoint(path="jobs/{id_}/")
    cancel_job = JsonEndpoint(path="jobs/{id_}/cancel/", default_method="POST")
    pause_job = JsonEndpoint(path="jobs/{id_}/pause/", default_method="POST")
    resubmit_job = JsonEndpoint(path="jobs/{id_}/resubmit/",
                                default_method="POST")
    resume_job = JsonEndpoint(path="jobs/{id_}/resume/", default_method="POST")
    job_output = JsonEndpoint(path="jobs/{id_}/{key}/")

    peers = JsonEndpoint(path="peers/")
    peer = JsonEndpoint(path="peers/{peer}/")
    del_peer = JsonEndpoint(path="peers/{peer}/", default_method="DELETE")
    put_peer = JsonEndpoint(path="peers/{peer}/", default_method="PUT")
    store_peer = JsonEndpoint(path="peers/{peer}/store/",
                              default_method="POST")

    plugins = JsonEndpoint(path="plugins/")
    plugin = JsonEndpoint(path="plugins/{id_}/")
    plugins_js = Endpoint(path="plugins/explorer.js/")

    statistics = JsonEndpoint(path="statistics/")
    system = JsonEndpoint(path="system/")

    tools_create_archive = StreamingEndpoint(path="tools/create-archive/",
                                             default_method="POST")
    tools_create_dicom = StreamingEndpoint(path="tools/create-dicom/",
                                           default_method="POST")
    tools_create_media = StreamingEndpoint(path="tools/create-media/",
                                           default_method="POST")
    tools_create_media_extended = StreamingEndpoint(
        path="tools/create-media-extended/", default_method="POST")
    tools_default_encoding = Endpoint(path="tools/default-encoding/")
    tools_change_default_encoding = Endpoint(path="tools/default-encoding/",
                                             default_method="PUT")
    tools_post_default_encoding = JsonEndpoint(path="tools/default-encoding/",
                                               default_method="POST")
    tools_dicom_conformance = Endpoint(path="tools/dicom-conformance/")
    tools_execute_script = JsonEndpoint(path="tools/execute-script/",
                                        default_method="POST")
    tools_find = JsonEndpoint(path="tools/find/", default_method="POST")
    tools_generate_uid = Endpoint(path="tools/generate-uid/")
    tools_invalidate_tags = JsonEndpoint(path="tools/invalidate-tags/",
                                         default_method="POST")
    tools_lookup = JsonEndpoint(path="tools/lookup/", default_method="POST")
    tools_metrics = JsonEndpoint(path="tools/metrics/")
    tools_change_metrics = JsonEndpoint(path="tools/metrics/",
                                        default_method="PUT")
    tools_metrics_prometheus = JsonEndpoint(path="tools/metrics-prometheus/")
    tools_now = Endpoint(path="tools/now/")
    tools_now_local = Endpoint(path="tools/now-local/")
    tools_reconstruct = Endpoint(path="tools/reconstruct/",
                                 default_method="POST")
    tools_reset = JsonEndpoint(path="tools/reset/", default_method="POST")
    tools_shutdown = JsonEndpoint(path="tools/shutdown/",
                                  default_method="POST")
Exemple #7
0
def call(
    service: apiron.Service,
    endpoint: apiron.Endpoint,
    method: Optional[str] = None,
    session: Optional[requests.Session] = None,
    params: Optional[Dict[str, Any]] = None,
    data: Optional[Dict[str, Any]] = None,
    files: Optional[Dict[str, str]] = None,
    json: Optional[Dict[str, Any]] = None,
    headers: Optional[Dict[str, Any]] = None,
    cookies: Optional[Dict[str, Any]] = None,
    auth: Optional[Any] = None,
    encoding: Optional[str] = None,
    retry_spec: retry.Retry = DEFAULT_RETRY,
    timeout_spec: Timeout = DEFAULT_TIMEOUT,
    logger: Optional[logging.Logger] = None,
    allow_redirects: bool = True,
    return_raw_response_object: Optional[bool] = None,
    **kwargs,
):
    """
    :param Service service:
        The service that hosts the endpoint being called
    :param Endpoint endpoint:
        The endpoint being called
    :param str method:
        The HTTP method to use for the call
    :param requests.Session session:
        (optional)
        An existing session, useful for making many calls in a single session
        (default ``None``)
    :param dict params:
        (optional)
        ``GET`` parameters to send to the endpoint
        (default ``None``)
    :param dict data:
        (optional)
        ``POST`` data to send to the endpoint.
        A :class:`dict` will be form-encoded, while a :class:`str` will be sent raw
        (default ``None``)
    :param dict files:
        (optional)
        Dictionary of ``'filename': file-like-objects`` for multipart encoding upload.
        (default ``None``)
    :param dict json:
        (optional)
        A JSON-serializable dictionary that will be sent as the ``POST`` body
        (default ``None``)
    :param dict headers:
        HTTP Headers to send to the endpoint
        (default ``None``)
    :param dict cookies:
        Cookies to send to the endpoint
        (default ``None``)
    :param auth:
        An object suitable for the :class:`requests.Request` object's ``auth`` argument
    :param str encoding:
        The codec to use when decoding the response.
        Default behavior is to have ``requests`` guess the codec.
        (default ``None``)
    :param urllib3.util.retry.Retry retry_spec:
        (optional)
        An override of the retry behavior for this call.
        (default ``Retry(total=1, connect=1, read=1, status_forcelist=[500-level status codes])``)
    :param Timeout timeout_spec:
        (optional)
        An override of the timeout behavior for this call.
        (default ``Timeout(connection_timeout=1, read_timeout=3)``)
    :param logging.Logger logger:
        (optional)
        An existing logger for logging from the proper caller for better correlation
    :param bool allow_redirects:
        (optional)
        Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection
        (default ``True``)
    :param bool return_raw_response_object:
        Whether to return a :class:`requests.Response` object or call :func:`format_response` on it first.
        (Default ``False``)
    :param ``**kwargs``:
        Arguments to be formatted into the ``endpoint`` argument's ``path`` attribute
    :return:
        The result of ``endpoint``'s :func:`format_response`
    :rtype: The type returned by ``endpoint``'s :func:`format_response`
    :raises requests.RetryError:
        if retry threshold exceeded due to bad HTTP codes (default 500 range)
    :raises requests.ConnectionError:
        if retry threshold exceeded due to connection or request timeouts
    """
    logger = logger or LOGGER

    managing_session = not session
    guaranteed_session = _get_guaranteed_session(session)
    adapted_session = _adapt_session(guaranteed_session, adapters.HTTPAdapter(max_retries=retry_spec))

    method = method or endpoint.default_method

    auth = auth or getattr(session, "auth", None) or service.auth

    request = _build_request_object(
        adapted_session,
        service,
        endpoint,
        method=method,
        params=params,
        data=data,
        files=files,
        json=json,
        headers=headers,
        cookies=cookies,
        auth=auth,
        **kwargs,
    )

    logger.info("%s %s", method, request.url)

    response = adapted_session.send(
        request,
        timeout=(timeout_spec.connection_timeout, timeout_spec.read_timeout),
        stream=getattr(endpoint, "streaming", False),
        allow_redirects=allow_redirects,
        proxies=adapted_session.proxies or service.proxies,
    )

    logger.info(
        "%d %s%s",
        response.status_code,
        response.url,
        " ({} redirect(s))".format(len(response.history)) if response.history else "",
    )

    if managing_session:
        adapted_session.close()

    response.raise_for_status()

    if encoding:
        response.encoding = encoding

    # Use the explicitly passed in option, if any
    # Otherwise, use the endpoint's setting
    if return_raw_response_object is None:
        return_raw_response = endpoint.return_raw_response_object
    else:
        return_raw_response = return_raw_response_object

    return response if return_raw_response else endpoint.format_response(response)
Exemple #8
0
 def test_endpoints_when_one_endpoint(self, service):
     foo = Endpoint(path="/foo")
     service.foo = foo
     assert service.endpoints == {foo}