Prefer attachment_filename for mime type guessing in send_file #670

Closed
wants to merge 1 commit into
from

Conversation

3 participants

In send_file you can explicitly set the filename using attachment_filename, but when attempting to guess the mimetype previously the code would prefer the real filename, this reverses that preference.

Our use case is that the real filename on disk is just a hash, and so the mime type cant be guessed anyway. You can of course explicitly set the mime type as well, but imo if a filename is explicitly passed in that should take precedence

Darren Worrall
Set mimetype from attachment_filename in send_file
In send_file you can explicitly set the filename using attachment_filename,
but when attempting to guess the mimetype previously the code would
prefer the real filename, this reverses that preference.
Owner

mitsuhiko commented Jan 27, 2013

Not a fan of this at all. In that case you should rather lookup the mimetype yourself (and keep the original extension on the hash you have on the filesystem).

@mitsuhiko mitsuhiko closed this Jan 27, 2013

apiguy commented Feb 4, 2013

While I agree that the best practice here would be to maintain the extension on the hash itself, there are cases where that is outside of a developer's control. In that case you should use:

attachment_name = "myattachment.xml"
mimetype = mimetypes.guess_type(attachment_name)
send_file(my_file,
    mimetype=mimetype,
    as_attachment=True
    attachment_name=attachment_name)

or even better if you know the mimetypes you'll be using in advance you can use some partially applied function helpers like:

send_xml_file = functools.partial(mimetype='text/xml', as_attachment=True)

Then you can always use that function and be certain it will carry the 'text/xml' mimetype and be sent as an attachment:

send_xml_file(my_file, attachment_name=attachment_name)

Hope this helps someone who runs into this in the future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment