def _get_rendered_frame()

in pathology/dicom_proxy/frame_retrieval_util.py [0:0]


def _get_rendered_frame(transaction: _DicomStoreFrameTransaction) -> FrameData:
  """Returns result of rendered frame request.

  Caches frames in local redis.  Cache mannaged by LRU.
  Cache works across users and process.

  Args:
    transaction: DICOM Store query that returns requested frame data.

  Returns:
    Requested frame bytes encoding frame in jpeg or png format.

  Raises:
    _EmptyFrameURLError: Transaction URL empty.
    DicomFrameRequestError: HTTP error in DICOM frame request.
  """
  if not transaction.url:
    raise _EmptyFrameURLError()
  redis = redis_cache.RedisCache(transaction.enable_caching)
  cache_key = frame_lru_cache_key(transaction)
  result = redis.get(cache_key)
  if (
      result is not None
      and result.value is not None
      and result.value != CACHE_LOADING_FRAME_BYTES
  ):
    return FrameData(result.value, False)
  response = requests.get(transaction.url, headers=transaction.headers)
  if response.status_code != http.client.OK:
    raise DicomFrameRequestError(response)
  received_content_type = response.headers.get(_CONTENT_TYPE)
  expected_content_type = transaction.headers.get(_ACCEPT)
  if (
      received_content_type is None
      or received_content_type != expected_content_type
  ):
    raise DicomFrameRequestError(
        response,
        msg=(
            f'Invalid content type. Expected: {expected_content_type}; '
            f'Received: {received_content_type}'
        ),
    )
  response_bytes = response.content
  if response_bytes is None or not response_bytes:
    raise DicomFrameRequestError(
        response, msg='Frame request returned no data.'
    )
  redis.set(cache_key, response_bytes, ttl_sec=frame_cache_ttl())
  return FrameData(response_bytes, True)