0

I'm new to Python and working through my first exercise in converting monolithic code to individual functions. Its unclear to me where to put the validation logic in the below example. Could someone provide guidance?

Goal:

  • Determine if any of the request headers are None, empty or blank.

Example:

def get_request_headers():
    req_id = req.headers.get("requestor-id")
    req_cert_raw = req.headers.get("X-ARR-ClientCert")
    req_host = req.headers.get("X-FORWARDED-FOR")
    return req_id, req_cert_raw, req_host

request_headers = get_request_headers()

Where would I put the logic that checks the headers are not None, blank or empty?

  • In the get_request_headers function itself?
  • When calling get_request_headers()
  • Or in its own function (validate_request_headers or the like?)

I think the logic is something like:

if req_id and req_id.strip() and req_cert_raw and req_cert_raw.strip() and req_host and req_host.strip():
    return req_id, req_cert_raw, req_host
elif:
    not req_id or req_id.strip()
    return logging.error('Request ID is not valid')
elif:
    not req_cert_raw or req_cert_raw.strip()
    return logging.error('Request Cert is not valid')
elif:
    not req_host or req_host.strip()
    return logging.error('Request Host is not valid')

But I'm unsure where to put it.

ericOnline
  • 1,586
  • 1
  • 19
  • 54
  • Do you have to check for the `.strip()` parts? If `if req_id` fails, it won't have a `.strip()`, no? – BruceWayne Nov 02 '20 at 18:10
  • Hi @BruceWayne, I was following the pattern in [this post](https://stackoverflow.com/a/24534152/10426490) for testing a string for `None`, empty or blank. – ericOnline Nov 02 '20 at 18:18

1 Answers1

2

This is more a matter of opinion but something like this might be okay, where it fails on empty string being None for strip, and then asserts the strings exist:

def get_request_headers():
    try:
        req_id = req.headers.get("requestor-id", None).strip()
        req_cert_raw = req.headers.get("X-ARR-ClientCert", None).strip()
        req_host = req.headers.get("X-FORWARDED-FOR", None).strip()
        assert req_id, f'Request ID is not valid: "{req_id}"'
        assert req_cert_raw, f'Request Cert is not valid: "{req_cert_raw}"'
        assert req_host, f'Request Host is not valid: "{req_host}"'
    except Exception as e:
        logging.error(e)
        raise
    return req_id, req_cert_raw, req_host
jmunsch
  • 22,771
  • 11
  • 93
  • 114
  • Any concerns about [using `assert`](https://stackoverflow.com/a/54113223/10426490) in production code? (Speaking from a COMPLETELY naive perspective; just read this recently so its fresh in my mind.) – ericOnline Nov 02 '20 at 18:23
  • 1
    @ericOnline would be something you'll need to check. I've never personally run into the issue, but then again haven't used the `-O` flag. Thanks for that, learned something new today. – jmunsch Nov 02 '20 at 18:31