Reputation: 155
I fetch files from an s3 bucket as binary blobs and have to return them via an http response with valid mime type (image/png, text/html, etc.). I found a package called mimetype
in the standard library that can to do this kind of things but it requires as an argument a path to a file on the file-system and thus an unnecessary write-read operation that I realy want to avoid.
import mimetypes
print(mimetypes.guess_type('test.jpg'))
# ('image/jpeg', None)
Can someone suggest a tool for guessing mime types for the files which are already loaded into memory and stored there as Python's bytes
type.
Upvotes: 0
Views: 691
Reputation: 661
mimetypes.guess_type()
does not require an IO operation. So just use that.
The docs say:
Guess the type of a file based on its filename, path or URL, given by url. URL can be a string or a path-like object.
So it's just looking at the string you've provided, not actually opening the file. We can confirm that by looking at the source, it's basically just comparing the extension to known filetypes.
Upvotes: 2