[Python] Python and forcing the download of a file

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I currently have the below code which works great as long as the response on the GET has the content-disposition header. However the problem comes in when there is no header. Normally this would indicate viewing the file in the browser. Is there a way to force the download from within Python?

    def action_download(doc_list):
    i = 0
    for doc in doc_list:
    try:
    r = requests.get(doc)
    filename = re.search('filename="(.*)"', r.headers['content-disposition']).group(1)
    with open(filename, "w") as code:
    i += 1
    code.write(r.content)
    code.close()
    except requests.exceptions.ConnectionError:
    print '\nError: File Not Found Server Side'
    print doc
    except Exception:
    print '\nUnknown Error'
    print doc
    print r.headers
    traceback.print_exc()
    continue
    if i < 1:
    sys.exit()


    UPDATED CODE BASED ON RESPONSES

    Defining the filename and passing the data content via hte write function works perfectly. Updated code below for anyone coming across the problem.

    *Note the addition in the KeyError exception.

    def action_download(doc_list):
    i = 0
    for doc in doc_list:
    try:
    r = requests.get(doc)
    filename = re.search('filename="(.*)"', r.headers['content-disposition']).group(1)
    with open(filename, "w") as code:
    i += 1
    code.write(r.content)
    code.close()
    except requests.exceptions.ConnectionError:
    print '\nError: File Not Found Server Side'
    print doc
    except KeyError:
    temp = str(doc).rsplit('.', 1)[1]
    ext = re.sub(r'\?.*', r'', temp)
    filename = "file{}.{}".format(i, ext.replace('?T', ''))
    with open(filename, "w") as code:
    i += 1
    code.write(r.content)
    code.close()
    continue
    except Exception:
    print '\nUnknown Error'
    print doc
    print r.headers
    traceback.print_exc()
    continue
    if i < 1:
    sys.exit()

    Continue reading...

Compartilhe esta Página