(requests, service_request, case_id, attempt=0)
Uses `ETag`_ to prevent a race condition.

    .. _ETag: https://www.hl7.org/fhir/http.html#concurrency
Uses `ETag`_ to prevent a race condition.
Uses ETag _ to prevent a race condition .
def claim_service_request(requests, service_request, case_id, attempt=0):
    """
    Uses `ETag`_ to prevent a race condition.

    .. _ETag: https://www.hl7.org/fhir/http.html#concurrency
    """
    endpoint = f"ServiceRequest/{service_request['id']}"
    response = requests.get(endpoint, raise_for_status=True)
    etag = response.headers['ETag']
    service_request = response.json()
    if service_request['status'] != 'active':
        raise ServiceRequestNotActive

    service_request['status'] = 'on-hold'
    service_request.setdefault('identifier', [])
    has_case_id = any(id_.get('system') == SYSTEM_URI_CASE_ID
                      for id_ in service_request['identifier'])
    if not has_case_id:
        service_request['identifier'].append({
            'system': SYSTEM_URI_CASE_ID,
            'value': case_id,
        })
    headers = {'If-Match': etag}
    response = requests.put(endpoint, json=service_request, headers=headers)
    if 200 <= response.status_code < 300:
        return service_request
    if response.status_code == 412 and attempt < 3:
        # ETag didn't match. Try again.
        return claim_service_request(requests, service_request, case_id, attempt + 1)
    else:
        response.raise_for_status()
def claim_service_request ( requests , service_request , case_id , attempt = 0 ) : endpoint = f"ServiceRequest/{service_request['id']}" response = requests . get ( endpoint , raise_for_status = True ) etag = response . headers [ 'ETag' ] service_request = response . json ( ) if service_request [ 'status' ] != 'active' : raise ServiceRequestNotActive service_request [ 'status' ] = 'on-hold' service_request . setdefault ( 'identifier' , [ ] ) has_case_id = any ( id_ . get ( 'system' ) == SYSTEM_URI_CASE_ID for id_ in service_request [ 'identifier' ] ) if not has_case_id : service_request [ 'identifier' ] . append ( { 'system' : SYSTEM_URI_CASE_ID , 'value' : case_id , } ) headers = { 'If-Match' : etag } response = requests . put ( endpoint , json = service_request , headers = headers ) if 200 <= response . status_code < 300 : return service_request if response . status_code == 412 and attempt < 3 : # ETag didn't match. Try again. return claim_service_request ( requests , service_request , case_id , attempt + 1 ) else : response . raise_for_status ( )