openfaas / python-flask-template

HTTP and Flask-based OpenFaaS templates for Python 3
MIT License
85 stars 86 forks source link

Support multiple return types in the http-templates #70

Closed welteki closed 6 months ago

welteki commented 9 months ago

Description

Allow users to use the Flask Response object and other functions like send_file. This makes it possible to stream a response or return files.

For backwards compatibility the response is still formatted like before when a dict object type is returned by the handler.

Motivation and Context

Returning large files and binary response was not supported by the python3-http template.

How Has This Been Tested?

Tested manually by converting a function example that creates a video-preview for a function using FFmpeg and returns the resulting video.

import os
import json
import logging
import tempfile
import ffmpeg
from flask import send_file

from .preview import generate_video_preview, calculate_sample_seconds

debug = os.getenv("debug", "false").lower() == "true"

def handle(event, context):
    request_data = json.loads(event.body)

    data, status_code, message = parse_request(request_data)
    if data is None:
        return {
            "statusCode": status_code,
            "body": message
        }

    input_url = data["input_url"]
    sample_duration = data["sample_duration"]
    sample_seconds = data["sample_seconds"]
    scale = data["scale"]
    format = data["format"]

    out_file = tempfile.NamedTemporaryFile(delete=True)

    # Generate video preview
    try:
        generate_video_preview(input_url, out_file.name, sample_duration, sample_seconds, scale, format, quiet=not debug)
    except Exception as e:
        logging.error(e)
        return {
            "statusCode": 500,
            "body": "failed to generate video preview"
        }

    return send_file(out_file.name)

Types of changes

Checklist: