ericOnline
ericOnline

Reputation: 2008

How to pass different HttpResponses within Python Azure Function?

I'm trying to find the pattern for returning different HttpResponse's based on checks throughout my HTTP Triggered, Python Azure Function.

Example:

import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:

    logging.info('####### HTTPS trigger processing an event... #######')

    def get_request_headers():
        thing_id = req.headers.get("thing-id")
        req_host_ip = req.headers.get("X-FORWARDED-FOR")

        return thing_id, req_host_ip


    def check_thing_id_hdr(thing_id):
        if (
            thing_id != None
            and thing_id.isnumeric() == True
            and len(thing_id) == 20
        ):
            return True
        else:
            # DO I RETURN THE HTTPRESPONSE HERE?
            return func.HttpResponse(
                'Thing ID header is malformed',
                status_code = 404
            )

    def check_req_host_ip_hdr(req_host_ip):
        if (
            req_host_ip.split(':')[0] != None
        ):
            return True
        else:
            # DO I RETURN THE HTTPRESPONSE HERE?
            return func.HttpResponse(
                'Host IP header is malformed',
                status_code = 404
            )

    request_headers = get_request_headers()

    if(check_thing_id_hdr(request_headers[0]) == True:
        check_req_host_ip_hdr(request_headers[1])
    else:
        logging.error('####### Thing ID header failed check. #######')
        # OR DO I DEFINE THE HTTPRESPONSE HERE? 
        func.HttpResponse(
            'Thing ID header is malformed',
            status_code = 404
        )

# OR DO I SOMEHOW DEFINE THE CUSTOM RESPONSE HERE?
return func.HttpResponse(
        'Custom Message HERE',
        status_code = Custom Status Code HERE
    )

I've tried the above patterns along with wrapping all internal functions with a big try:-except:, but none of them return the custom message.

Please advise.

Upvotes: 2

Views: 683

Answers (1)

suziki
suziki

Reputation: 14113

Is below code what you want?

import logging

import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:

    #For example, use the param as the condition.
    condition = req.params.get('condition')
    if condition == "success":
        return func.HttpResponse(
             "Success.",
             status_code=200
        )
    elif condition == "not_success":
        return func.HttpResponse(
             "Not success.",
             status_code=400
        )
    else:
        return func.HttpResponse(
             "No condition.",
             status_code=404
        )

Upvotes: 1

Related Questions