I am downloading a file with Mechanize and in response headers there is a string:
Content-Disposition: attachment; filename=myfilename.txt
Is there a quick standard way to get that filename value? What I have in mind now is this:
filename = f[1]['Content-Disposition'].split('; ')[1].replace('filename=', '')
But it looks like a quick'n'dirty solution.
I would try something like:
This handles quotes and URL escaping on the filenames.
First get the value of the header by using mechanize, then parse the header using the builtin cgi module.
To demonstrate:
The header value can then be parsed:
params
is a simple dict soparams['filename']
is what you need. It doesn't matter whether the filename is wrapped in quotes or not.These regular expressions are based on the grammar from RFC 6266, but modified to accept headers without disposition-type, e.g. Content-Disposition: filename=example.html
i.e. [ disposition-type ";" ] disposition-parm ( ";" disposition-parm )* / disposition-type
It will handle filename parameters with and without quotes, and unquote quoted pairs from values in quotes, e.g. filename="foo\"bar" -> foo"bar
It will handle filename* extended parameters and prefer a filename* extended parameter over a filename parameter regardless of the order they appear in the header
It strips folder name information, e.g. /etc/passwd -> passwd, and it defaults to the basename from the URL path in the absence of a filename parameter (or header, or if the parameter value is empty string)
The token and qdtext regular expressions are based on the grammar from RFC 2616, the mimeCharset and valueChars regular expressions are based on the grammar from RFC 5987, and the language regular expression is based on the grammar from RFC 5646