ericOnline
ericOnline

Reputation: 1967

Where to validate strings in Python function?

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:

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?

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.

Upvotes: 0

Views: 82

Answers (1)

jmunsch
jmunsch

Reputation: 24089

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

Upvotes: 2

Related Questions