pythonamazon-web-servicesaws-lambdamime-types

How to best use Python 3's mimetypes module in AWS Lambda?


I deployed a working Flask application to AWS Lambda via Zappa. One of the things working locally but not on Lambda is the call to

mimetypes.guess_extension

In particular, locally, on my Mac, the guessed extension for

application/vnd.openxmlformats-officedocument.wordprocessingml.document

is properly

.docx

but on Lambda, it's

None

The way mimetypes works is that it consults the host machine's mime.types file, and this file either does not exist on Lambda or something does but it does not have many types.

So how can get this module to work on Lambda? The documentation mentions an init function in the module which accepts files, but that doesn't seem right for a Lambda. I could, I guess bundle up the entire 48K mime.types file on my Mac into my deployed Lambda (as a file?), but that seems like overkill, and was wondering if perhaps I missed something and that Lambdas should have access to this information without uploading files?

I checked PyPI and found the packages mime and common-mimetypes but they have not been touched in years.

Any best practices I am overlooking here?


Solution

  • I think based on the structure of AWS lambda, it won't contain what you want or at least all of you want.

    Instead of uploading a file to lambda, I will suggest to upload the file to some cloud storage like your s3 storage. And initialize your program using that file without storing it on disk.

    mime = MimeTypes()
    with requests.get(url) as res:
        mime_file = BytesIO(res.content)
    mime.readfp(mime_file)
    
    mime.guess_extension("application/vnd.openxmlformats-officedocument.wordprocessingml.document")