def index()

in data-loss-prevention/code/redact/app.py [0:0]


def index():
    """Receive and parse Pub/Sub messages.

    This function handles incoming HTTP POST requests, expecting a Pub/Sub
    message in the request body. It parses the message, extracts the
    `textPayload` from the message data, and redacts sensitive information
    within the payload using the `redact_dlp_item` function.

    Returns:
        tuple: An empty tuple and a 204 status code indicating successful
               processing of the Pub/Sub message.
    """
    recevied_msg = request.get_json()
    if not recevied_msg:
        msg = "no Pub/Sub message received"
        print(f"error: {msg}")
        logging.error(f"error: {msg}")
        return f"Bad Request: {msg}", 400

    if not isinstance(recevied_msg, dict) or "message" not in recevied_msg:
        msg = "invalid Pub/Sub message format"
        print(f"error: {msg}")
        logging.error(f"error: {msg}")
        return f"Bad Request: {msg}", 400

    pubsub_message = recevied_msg["message"]

    if isinstance(pubsub_message, dict) and "data" in pubsub_message:
        msg = json.loads(
            base64.b64decode(pubsub_message["data"]).decode("utf-8").strip()
        )
        payload = msg["textPayload"]
        jsopn_payload = ast.literal_eval(payload)
        if isinstance(jsopn_payload, dict):
            for key, _ in jsopn_payload.items():
                redact_item = redact_dlp_item(
                    project_id=os.environ.get("PROJECT_ID"),
                    inspect_item=jsopn_payload[key]
                )
                jsopn_payload[key] = redact_item
            logging.info(jsopn_payload)
    return ("", 204)